@zuplo/runtime 6.63.32 → 6.63.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/index.js +1 -1
- package/out/esm/index.js.map +1 -1
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -84,7 +84,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
84
84
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!v.has("X-Amz-Expires")&&v.set("X-Amz-Expires","86400"),v.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),v.set("X-Amz-Credential",`${this.accessKeyId}/${this.credentialString}`),v.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Zh(this.encodedPath);let T=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(T.has(A))return!1;T.add(A)}return!0}).map(A=>A.map(C=>Zh(encodeURIComponent(C)))).sort(([A,C],[S,N])=>A<S?-1:A>S?1:C<N?-1:C>N?1:0).map(A=>A.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,`SignedHeaders=${this.signedHeaders}`,`Signature=${await this.signature()}`].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let o=await Jn(`AWS4${this.secretAccessKey}`,e),i=await Jn(o,this.region),a=await Jn(i,this.service);n=await Jn(a,"aws4_request"),this.cache.set(r,n)}return Ic(await Jn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ic(await jh(await this.canonicalString()))].join(`
|
|
85
85
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,`${this.canonicalHeaders}
|
|
86
86
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
87
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new F("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Ic(await jh(this.body||""))}return e}};async function Jn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Sc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Sc.encode(e))}s(Jn,"hmac");async function jh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Sc.encode(t):t)}s(jh,"hash");function Ic(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Ic,"buf2hex");function Zh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Zh,"encodeRfc3986");function lP(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")r.startsWith("iot.")?i="execute-api":r.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in zh?[zh[i],a]:[i,a]}s(lP,"guessServiceRegion");function dP(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(dP,"b64ToUint6");function qh(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=dP(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(qh,"base64Decode");function Mi(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Mi,"uint6ToB64");function Fh(t){let e=2,r="",n=t.length,o=0;for(let i=0;i<n;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(r+=String.fromCodePoint(Mi(o>>>18&63),Mi(o>>>12&63),Mi(o>>>6&63),Mi(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(Fh,"base64Encode");function Br(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Br,"numberToString");function pP(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Br(Math.floor(r/60)),i=Br(r%60);return`${n}${o}${i}`}s(pP,"getCLFOffset");function Tc(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Br(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),i=Br(t.getHours()),a=Br(t.getMinutes()),c=Br(t.getSeconds()),u=pP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Tc,"toCLFDate");var Hh=Ne("zuplo:runtime"),Vr="X-Amzn-Trace-Id",mP="x-amzn-errortype",Gh=[],fP=s(async(t,e,r)=>{let n=r;for await(let o of Gh)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),nt=class extends F{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Vr)??void 0,this.errorType=r.get(mP)??void 0}},gP={addSendingAwsLambdaEventHook:s(t=>{Gh.push(t)},"addSendingAwsLambdaEventHook")};async function hP(t,e){R("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new w("awsAccessKeyId is not set in the handler options");if(!n)throw new w("secretAccessKey is not set in the handler options");if(!o)throw new w("region is not set in the handler options");if(!i)throw new w("functionName is not set in the handler options");let l=new Gr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Hh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await vP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=wP(t,e):g=await bP(t,e,{useAwsResourcePathStyle:c}),Hh("Calling onSendingAwsLambdaEvent hook");let b=await fP(t,e,g);b.body=p,b.isBase64Encoded=m;let h=await l.fetch(d,{body:JSON.stringify(b)}),x=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&typeof f.returnAmazonTraceIdHeader=="boolean"?f.returnAmazonTraceIdHeader:!1;try{return yP(h,{returnLambdaTraceIdHeader:x})}catch(v){if(v instanceof nt){let T=x&&v.traceId?{[Vr]:v.traceId}:void 0;return D.internalServerError(t,e,void 0,T)}throw v}}s(hP,"awsLambdaHandler");async function yP(t,{returnLambdaTraceIdHeader:e}){let r;try{r=await t.json()}catch{throw new nt("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?new nt(r.message,t.headers):new nt(`Status: ${t.statusText}`,t.headers);if(r&&typeof r=="object"&&"errorMessage"in r&&typeof r.errorMessage=="string")throw new nt(r.errorMessage,t.headers);if(!r||typeof r!="object"||!("statusCode"in r)||typeof r.statusCode!="number"){let a=t.headers.get(Vr);return new Response(JSON.stringify(r),{status:t.status,headers:{"content-type":"application/json",...e&&a?{[Vr]:a}:{}}})}let n=new Headers;if("headers"in r&&r.headers){if(typeof r.headers!="object")throw new nt(`Response headers must be an object. Received ${typeof r.headers}`,t.headers);for(let[a,c]of Object.entries(r.headers))n.set(a,c)}if("cookies"in r&&r.cookies){if(!Array.isArray(r.cookies))throw new nt(`Response cookies must be an array. Received ${typeof r.cookies}`,t.headers);n.set("cookie",r.cookies.join(";"))}let o;if("isBase64Encoded"in r&&typeof r.isBase64Encoded!="boolean")throw new nt(`Response property isBase64Encoded must be a boolean. Received ${typeof r.isBase64Encoded}`,t.headers);if("isBase64Encoded"in r&&r.isBase64Encoded===!0){if(!("body"in r))throw new nt("Response was set to base64 encoded but no body was set",t.headers);if(typeof r.body!="string")throw new nt("Response was set to base64 encoded but body was not a string",t.headers);o=qh(r.body)}else"body"in r&&typeof r.body=="string"?o=r.statusCode===204&&r.body===""?null:r.body:"body"in r&&r.body!==null&&r.body!==void 0?o=JSON.stringify(r.body):o=null;if(o!==null&&"bodyEncoding"in r){if(typeof r.bodyEncoding!="string"||!(r.bodyEncoding==="gzip"||r.bodyEncoding==="deflate"))throw new nt(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${r.bodyEncoding}`,t.headers);let a=new Blob([o]).stream().pipeThrough(new DecompressionStream(r.bodyEncoding));o=await new Response(a).arrayBuffer()}let i=t.headers.get(Vr);return e&&i&&n.set(Vr,i),new Response(o,{headers:n,status:r.statusCode})}s(yP,"getResponse");async function bP(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Tc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:RP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(bP,"buildEventVersion1");function wP(t,e){let r={};t.headers.forEach((i,a)=>{r[a]=i});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Tc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(wP,"buildEventVersion2");async function vP(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&xP(e,o)){let i=await t.arrayBuffer();r=Fh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(vP,"getBodyResult");function xP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(xP,"matchesContentType");function RP(t,e=!1){if(!e)return t;let r=Pc(t),n=Uh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(RP,"getResourcePath");var PP=[502,503,504];async function Jr(t,e){if(PP.includes(t.status)){let r=K.getLogger(e),o=await t.clone().text(),i={};for(let[a,c]of t.headers)i[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Jr,"logBadGatewayResponses");var Ec;function Qt(t){if(Ec===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Ec=r}return t.log[Ec]}s(Qt,"getHandlerUserLogFunction");async function IP(t,e){R("handler.open-api");let r=P.instance.build.BUILD_ID,{buildAssetsUrl:n}=P.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new w("Open API Spec Handler must have 'openApiFilePath' specified");let a=SP(i);if(!a.isValid)throw new w(a.error);let c=`${n}/${r}${i.substring(1)}`,u=await z.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return D.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};P.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return Jr(d,e),d}s(IP,"openApiSpecHandler");var SP=s(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");async function kP(t,e){R("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new w("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}s(kP,"redirectHandler");async function TP(t){if(R("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new w("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,P.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${P.instance.authApiJWT}`),z.fetch(e,{method:t.method,headers:r,body:t.body})}s(TP,"zuploServiceProxy");function EP(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}s(EP,"join");async function CP(t,e){R("handler.url-forward");let r=Qt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i;if(P.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&R("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Kt(e),c=new URL(t.url),u=n.__rewriteFunction(t,a),l=EP(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=t.body;if(i==="follow"&&t.body)try{m=await t.arrayBuffer()}catch(b){throw new Error(`Failed to buffer request body for redirect handling: ${b}`)}let f=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${f.status} - ${f.statusText} in ${g}ms`),Jr(f,e),f}s(CP,"urlForwardHandler");var _P=s((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,i]of n.searchParams.entries())r.searchParams.append(o,i);return r.toString()},"addQuery");async function OP(t,e){R("handler.url-rewrite");let r=Qt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Kt(e),c=n.__rewriteFunction(t,a),u=o?_P(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual",zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Jr(d,e),d}s(OP,"urlRewriteHandler");function $P(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",n=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(n)}`),e.send(JSON.stringify(n))}),e.addEventListener("error",n=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(n)}`),t.send(JSON.stringify(n))}),t.addEventListener("message",n=>{e.send(n.data)}),e.addEventListener("message",n=>{t.send(n.data)})}s($P,"wireUpPassthrough");async function AP(t,e){R("handler.websocket");let r=e.route.handler.options,n=Qt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Kt(e),a=r.__rewriteFunction(t,i);if(n(`Attempting WebSocket connection to '${a}'`),P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let c=new WebSocket(a);await new Promise((d,p)=>{let m=s(()=>{g(),n("WebSocket connection established with upstream"),d()},"onOpen"),f=s(b=>{g(),n(`WebSocket connection error: ${b}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",f)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",f)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return $P(u,c,e),l}else{a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let u=await c.text(),l=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${u}'`;throw new Error(l)}return n(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(AP,"webSocketHandler");var Bh=s((t,e)=>{let{mode:r}=e.route.handler.options,n=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!n)throw new w("Developer portal URL is not configured.");if(r==="proxy"){let o=new URL(t.url);return o.hostname=new URL(n).hostname,z.fetch(o,{method:t.method,headers:t.headers,body:t.body})}else{let o=NP(t.url,n);return new Response(null,{status:301,headers:{location:o}})}},"legacyDevPortalHandler");function NP(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new w("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}s(NP,"getDevPortalRedirectUrl");var LP=Bh;var Cc=s((t,e)=>t.map((n,o)=>{let i;if(typeof n.module=="object"&&(i=n.module[n.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${n.export}`;throw new w(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),Vh=s(async(t,e,r,n,o,i)=>{let a=t.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");async function MP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=new WebSocket(e);await new Promise((a,c)=>{let u=s(()=>{d(),r("WebSocket connection established with upstream"),a()},"onOpen"),l=s(p=>{d(),r(`WebSocket connection error: ${p}`),c(new Error("Upstream open failed"))},"onErr"),d=s(()=>{n.removeEventListener("open",u),n.removeEventListener("error",l)},"cleanup");n.addEventListener("open",u),n.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:o,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:o,outgoingSocket:n,response:i}}s(MP,"getDenoClientAndServerSockets");async function DP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(n.status!==101||!n.webSocket){let u=await n.text(),l=`WebSocket connection error - ${n.status}: ${n.statusText}, content: '${u}'`;throw new Error(l)}let o=new WebSocketPair,[i,a]=Object.values(o);r(`WebSocket connected, received response ${n.status} - ${n.statusText}`),n.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{clientSocket:i,outgoingSocket:n.webSocket,serverSocket:a,response:c}}s(DP,"getCfClientAndServerSockets");function Jh(t,e,r,n,o,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{n.log.error(`WebSocket error: ${JSON.stringify(a)}, direction: ${i}`),e.send(JSON.stringify(a))}),t.addEventListener("message",a=>{try{let u=s(async l=>{let d=await Vh(l,t,e,r,n,o);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(n.log.error);n.waitUntil(u)}catch(c){n.log.error(c)}})}s(Jh,"wireUpListeners");async function UP(t,e){R("handler.websocket-pipeline");let r=e.route.handler.options,n=Qt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Kt(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?Cc(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?Cc(r.policies.outbound,"outbound"):[],l,d,p,m;if(P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let f=await MP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await DP(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Jh(l,d,t,e,c,"inbound"),Jh(d,l,t,e,u,"outbound"),m}s(UP,"webSocketPipelineHandler");Ze();er();er();function Sr({id:t,method:e,params:r}){return{jsonrpc:pt,id:t,method:e,params:r}}s(Sr,"newJSONRPCRequest");function Ct({id:t,result:e}){return{jsonrpc:pt,id:t,result:e}}s(Ct,"newJSONRPCReponse");function ke({id:t,code:e,message:r,data:n}){return{jsonrpc:pt,id:t,error:{code:e,message:r,data:n}}}s(ke,"newJSONRPCError");Ze();er();Zs();var Nw=y.object({jsonrpc:y.literal(pt),id:Aw,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();Mo();kr();Tr();var Do=s(t=>Mw.safeParse(t).success,"isJSONRPCRequest"),Uw=s(t=>Lw.safeParse(t).success,"isJSONRPCNotification"),on=s(t=>Dw.safeParse(t).success,"isJSONRPCResponse"),rr=s(t=>Nw.safeParse(t).success,"isJSONRPCError");var Uo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function nr(){return new Uo}s(nr,"createDefaultLogger");Ze();kr();Tr();Ze();var zw=y.object({experimental:y.optional(y.object({}).loose()),roots:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),sampling:y.optional(y.object({}).loose()),elicitation:y.optional(y.object({}).loose())}).loose(),jw=y.object({experimental:y.optional(y.object({}).loose()),logging:y.optional(y.object({}).loose()),completions:y.optional(y.object({}).loose()),prompts:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),resources:y.optional(y.object({subscribe:y.optional(y.boolean()),listChanged:y.optional(y.boolean())}).loose()),tools:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose())}).loose();Ze();sn();var nm=_t.extend({version:y.string()});var Zw=at.extend({method:y.literal("initialize"),params:st.extend({protocolVersion:y.string(),capabilities:zw,clientInfo:nm})}),GF=mt.extend({protocolVersion:y.string(),capabilities:jw,serverInfo:nm,instructions:y.optional(y.string())});Ze();Mo();kr();Tr();sn();qs();var jE=_t.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),ZE=_t.extend({description:y.optional(y.string()),arguments:y.optional(y.array(jE)),_meta:y.optional(y.object({}).loose())}),qE=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(sm(),Xo(im)),{ResourceLinkSchema:o}=(Fs(),Xo(pm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Vw=ir.extend({method:y.literal("prompts/list")}),hH=sr.extend({prompts:y.array(ZE)}),Jw=at.extend({method:y.literal("prompts/get"),params:st.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),yH=mt.extend({description:y.optional(y.string()),messages:y.array(qE)}),bH=tr.extend({method:y.literal("notifications/prompts/list_changed")});Fs();Ze();Mo();kr();Tr();sn();qs();var FE=y.object({title:y.optional(y.string()),readOnlyHint:y.optional(y.boolean()),destructiveHint:y.optional(y.boolean()),idempotentHint:y.optional(y.boolean()),openWorldHint:y.optional(y.boolean())}).loose(),HE=_t.extend({description:y.optional(y.string()),inputSchema:y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose(),outputSchema:y.optional(y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose()),annotations:y.optional(FE),_meta:y.optional(y.object({}).loose())}),kH=ir.extend({method:y.literal("tools/list")}),TH=sr.extend({tools:y.array(HE)}),Ww=at.extend({method:y.literal("tools/call"),params:st.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),EH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(sm(),Xo(im)),{ResourceLinkSchema:o}=(Fs(),Xo(pm));return mt.extend({content:y.array(y.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:y.optional(y.record(y.string(),y.unknown())),isError:y.optional(y.boolean())})}),CH=tr.extend({method:y.literal("notifications/tools/list_changed")});var zo="2025-06-18",mm="2025-03-26",fm="2024-11-05",gm="2024-10-07",hm=[zo,mm,fm,gm];var GE="MCP Server",BE="0.0.0",Hs=class{static{s(this,"MCPServer")}capabilities;tools=new Map;prompts=new Map;resources=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||GE,this.version=e.version||BE,this.instructions=e.instructions||void 0,this.logger=e.logger||nr(),this.capabilities={tools:{supported:!0,available:[]},prompts:{},resources:{},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(Do(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Uw(r))return await this.handleNotification(r),null;if(on(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),Do(r)){let o=ke({id:r.id,code:Se.InternalError,message:n instanceof Error?n.message:"Internal error"});return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:i=`Execute the ${r} tool`,outputSchema:a}=e,u={tool:{name:r,description:i,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,u),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}addPrompt(e){let{name:r,validator:n,generator:o,description:i}=e,a=n.jsonSchema,c;if(a.properties&&typeof a.properties=="object"){let d=new Set(a.required||[]);c=Object.entries(a.properties).map(([p,m])=>({name:p,description:m.description??`Prompt for ${p}`,required:d.has(p)}))}let l={prompt:{name:r,description:i,...c&&{arguments:c}},validator:n,generator:o};this.prompts.set(r,l)}removePrompt(e){return this.prompts.delete(e)}getPrompt(e){return this.prompts.get(e)?.prompt}getPromptDefinitions(){return Array.from(this.prompts.values()).map(e=>e.prompt)}addResource(e,r,n,o){if(typeof r=="string"){let a={type:"resource",resource:{name:e,uri:r,...n},reader:o};this.resources.set(e,a)}else{let a={type:"template",template:{name:e,uriTemplate:r.template,...n},reader:o};this.resources.set(e,a)}}removeResource(e){return this.resources.delete(e)}getResource(e){let r=this.resources.get(e);if(r)return r.type==="resource"?r.resource:void 0}getResourceTemplate(e){let r=this.resources.get(e);if(r)return r.type==="template"?r.template:void 0}getResourceDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="resource").map(e=>e.resource)}getResourceTemplateDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="template").map(e=>e.template)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);case"prompts/list":return this.handlePromptListRequest(e);case"prompts/get":return this.handlePromptGetRequest(e);case"resources/list":return this.handleResourceListRequest(e);case"resources/templates/list":return this.handleResourceTemplateListRequest(e);case"resources/read":return this.handleResourceReadRequest(e);default:return ke({id:e.id,code:Se.MethodNotFound,message:`Method "${e.method}" not found`})}}catch(r){return this.logger.error("Error handling request:",r),ke({id:e.id,code:Se.InternalError,message:r instanceof Error?r.message:"Internal error"})}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return Ct({id:e.id,result:{}})}handleInitialize(e){let r=Zw.safeParse(e);if(!r.success){let o=y.treeifyError(r.error),i=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${i}`,data:o})}let n=r.data.params.protocolVersion;switch(n){case zo:case mm:case fm:case gm:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return Ct({id:e.id,result:o})}default:return ke({id:e.id,code:Se.InvalidParams,message:`Unsupported protocol version: ${n} - supported versions: ${hm}`,data:{supportedVersions:hm}})}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return Ct({id:e.id,result:n})}async handleToolCallRequest(e){let r=Ww.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),ke({id:e.id,code:Se.InvalidRequest,message:`Invalid request ${r.error}`});let n=r.data,o=n.params.name,i=this.tools.get(o);if(!i)return ke({id:e.id,code:Se.InvalidParams,message:`Tool "${o}" not found`});let a=n.params.arguments??{},c=i.validator.parse(a);if(!c.success)return ke({id:e.id,code:Se.InvalidParams,message:c.errorMessage?`Invalid arguments for tool '${o}': ${c.errorMessage}`:`Invalid arguments for tool '${o}'`,data:c.errorData});try{let u=c.data,l=await i.handler(u);return Ct({id:e.id,result:l})}catch(u){return this.logger.error(`Error executing tool "${o}":`,u),ke({id:e.id,code:Se.InternalError,message:u instanceof Error?u.message:"Tool execution error"})}}async handlePromptListRequest(e){let r=Vw.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={prompts:Array.from(this.prompts.values()).map(i=>i.prompt)};return Ct({id:e.id,result:o})}async handlePromptGetRequest(e){let r=Jw.safeParse(e);if(!r.success){let c=y.treeifyError(r.error),u=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${u}`,data:c})}let n=r.data.params.name,o=this.prompts.get(n);if(!o)return ke({id:e.id,code:Se.InvalidParams,message:`Prompt "${n}" not found`});let i=r.data.params.arguments??{},a=o.validator.parse(i);if(!a.success)return ke({id:e.id,code:Se.InvalidParams,message:a.errorMessage?`Invalid arguments for prompt '${n}': ${a.errorMessage}`:`Invalid arguments for prompt '${n}'`,data:a.errorData});try{let c=a.data,u=await o.generator(c),l={...o.prompt.description&&{description:o.prompt.description},messages:u};return Ct({id:e.id,result:l})}catch(c){return this.logger.error(`Error generating prompt "${n}":`,c),ke({id:e.id,code:Se.InternalError,message:c instanceof Error?c.message:"Prompt generation error"})}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}async handleResourceListRequest(e){let r=um.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resources:Array.from(this.resources.values()).filter(i=>i.type==="resource").map(i=>i.resource)};return Ct({id:e.id,result:o})}async handleResourceTemplateListRequest(e){let r=lm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resourceTemplates:Array.from(this.resources.values()).filter(i=>i.type==="template").map(i=>i.template)};return Ct({id:e.id,result:o})}async handleResourceReadRequest(e){let r=dm.safeParse(e);if(!r.success){let a=y.treeifyError(r.error),c=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${c}`,data:a})}let n=r.data.params.uri;function o(a,c){let u=c.replace(/\{[^}]+\}/g,"([^/]+)");return new RegExp(`^${u}$`).test(a)}s(o,"matchesTemplate");let i=Array.from(this.resources.values()).find(a=>a.type==="resource"&&a.resource.uri===n||a.type==="template"&&o(n,a.template.uriTemplate));if(!i)return ke({id:e.id,code:Se.ResourceNotFound,message:`Resource not found: ${n}`,data:{uri:n}});try{let a=await i.reader(n);return Ct({id:e.id,result:a})}catch(a){return this.logger.error(`Error reading resource "${n}":`,a),ke({id:e.id,code:Se.ResourceNotFound,message:a instanceof Error?a.message:"Resource not found",data:{uri:n}})}}};var ar=class{static{s(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};er();var Gs=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;headers;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;setHeaders(e){this.headers={...this.headers,...e}}constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.headers={"Content-Type":"application/json",...e.headers},this.logger=e.logger||nr(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(on(e)){for(let[r,n]of this.sessions.entries())for(let[o,i]of n.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),Do(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify(ke({code:-32e3,message:"Transport not connected",id:null})),{status:503,headers:this.headers});if(!this.messageHandler)return new Response(JSON.stringify(ke({code:-32e3,message:"No message handler registered",id:null})),{status:500,headers:this.headers});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){return this.logger.error("Error handling request:",n),new Response(JSON.stringify(ke({code:Se.InternalError,message:"Internal server error",id:null})),{status:400,headers:this.headers})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify(ke({code:Se.InvalidRequest,message:"Not Acceptable: Client must accept application/json and text/event-stream",id:null})),{status:406,headers:this.headers});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify(ke({code:Se.ParseError,message:"Parse error: received invalid JSON",id:null})),{status:400,headers:this.headers});let i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=r;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let p of i)await this.messageHandler?.(p);return new Response(null,{status:202,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}if(!this.enableStreaming){let p=[];for(let f of i)if(this.isRequest(f)){let g=await this.messageHandler?.(f);g&&p.push(g)}else await this.messageHandler?.(f);let m=p.length===1?p[0]:p;return new Response(JSON.stringify(m),{status:200,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let p of i)if(this.isRequest(p)){this.streams.get(l)?.pendingRequests.add(p.id);let m=this.messageHandler?.(p);d.push(m)}else await this.messageHandler?.(p);return new Response(u.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}catch{return new Response(JSON.stringify(ke({code:Se.InternalError,message:"Internal server error",id:null})),{status:500,headers:this.headers})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:this.headers});if(this.options.enableSessions&&!r)return new Response(JSON.stringify(ke({code:Se.InvalidRequest,message:"Session ID required",id:null})),{status:400,headers:this.headers});let{stream:o,streamId:i}=this.createStream(r),a=e.headers.get("Last-Event-ID");return a&&r&&await this.replayMessages(r,i,a),new Response(o.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...r&&{"Mcp-Session-Id":r.id}}})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,i]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let i=`id: ${n}
|
|
87
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new F("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Ic(await jh(this.body||""))}return e}};async function Jn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Sc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Sc.encode(e))}s(Jn,"hmac");async function jh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Sc.encode(t):t)}s(jh,"hash");function Ic(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Ic,"buf2hex");function Zh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Zh,"encodeRfc3986");function lP(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")r.startsWith("iot.")?i="execute-api":r.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in zh?[zh[i],a]:[i,a]}s(lP,"guessServiceRegion");function dP(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(dP,"b64ToUint6");function qh(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=dP(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(qh,"base64Decode");function Mi(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Mi,"uint6ToB64");function Fh(t){let e=2,r="",n=t.length,o=0;for(let i=0;i<n;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(r+=String.fromCodePoint(Mi(o>>>18&63),Mi(o>>>12&63),Mi(o>>>6&63),Mi(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(Fh,"base64Encode");function Br(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Br,"numberToString");function pP(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Br(Math.floor(r/60)),i=Br(r%60);return`${n}${o}${i}`}s(pP,"getCLFOffset");function Tc(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Br(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),i=Br(t.getHours()),a=Br(t.getMinutes()),c=Br(t.getSeconds()),u=pP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Tc,"toCLFDate");var Hh=Ne("zuplo:runtime"),Vr="X-Amzn-Trace-Id",mP="x-amzn-errortype",Gh=[],fP=s(async(t,e,r)=>{let n=r;for await(let o of Gh)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),nt=class extends F{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Vr)??void 0,this.errorType=r.get(mP)??void 0}},gP={addSendingAwsLambdaEventHook:s(t=>{Gh.push(t)},"addSendingAwsLambdaEventHook")};async function hP(t,e){R("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new w("awsAccessKeyId is not set in the handler options");if(!n)throw new w("secretAccessKey is not set in the handler options");if(!o)throw new w("region is not set in the handler options");if(!i)throw new w("functionName is not set in the handler options");let l=new Gr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Hh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await vP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=wP(t,e):g=await bP(t,e,{useAwsResourcePathStyle:c}),Hh("Calling onSendingAwsLambdaEvent hook");let b=await fP(t,e,g);b.body=p,b.isBase64Encoded=m;let h=await l.fetch(d,{body:JSON.stringify(b)}),x=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&typeof f.returnAmazonTraceIdHeader=="boolean"?f.returnAmazonTraceIdHeader:!1;try{return yP(h,{returnLambdaTraceIdHeader:x})}catch(v){if(v instanceof nt){let T=x&&v.traceId?{[Vr]:v.traceId}:void 0;return D.internalServerError(t,e,void 0,T)}throw v}}s(hP,"awsLambdaHandler");async function yP(t,{returnLambdaTraceIdHeader:e}){let r;try{r=await t.json()}catch{throw new nt("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?new nt(r.message,t.headers):new nt(`Status: ${t.statusText}`,t.headers);if(r&&typeof r=="object"&&"errorMessage"in r&&typeof r.errorMessage=="string")throw new nt(r.errorMessage,t.headers);if(!r||typeof r!="object"||!("statusCode"in r)||typeof r.statusCode!="number"){let a=t.headers.get(Vr);return new Response(JSON.stringify(r),{status:t.status,headers:{"content-type":"application/json",...e&&a?{[Vr]:a}:{}}})}let n=new Headers;if("headers"in r&&r.headers){if(typeof r.headers!="object")throw new nt(`Response headers must be an object. Received ${typeof r.headers}`,t.headers);for(let[a,c]of Object.entries(r.headers))n.set(a,c)}if("cookies"in r&&r.cookies){if(!Array.isArray(r.cookies))throw new nt(`Response cookies must be an array. Received ${typeof r.cookies}`,t.headers);n.set("cookie",r.cookies.join(";"))}let o;if("isBase64Encoded"in r&&typeof r.isBase64Encoded!="boolean")throw new nt(`Response property isBase64Encoded must be a boolean. Received ${typeof r.isBase64Encoded}`,t.headers);if("isBase64Encoded"in r&&r.isBase64Encoded===!0){if(!("body"in r))throw new nt("Response was set to base64 encoded but no body was set",t.headers);if(typeof r.body!="string")throw new nt("Response was set to base64 encoded but body was not a string",t.headers);o=qh(r.body)}else"body"in r&&typeof r.body=="string"?o=r.statusCode===204&&r.body===""?null:r.body:"body"in r&&r.body!==null&&r.body!==void 0?o=JSON.stringify(r.body):o=null;if(o!==null&&"bodyEncoding"in r){if(typeof r.bodyEncoding!="string"||!(r.bodyEncoding==="gzip"||r.bodyEncoding==="deflate"))throw new nt(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${r.bodyEncoding}`,t.headers);let a=new Blob([o]).stream().pipeThrough(new DecompressionStream(r.bodyEncoding));o=await new Response(a).arrayBuffer()}let i=t.headers.get(Vr);return e&&i&&n.set(Vr,i),new Response(o,{headers:n,status:r.statusCode})}s(yP,"getResponse");async function bP(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Tc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:RP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(bP,"buildEventVersion1");function wP(t,e){let r={};t.headers.forEach((i,a)=>{r[a]=i});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Tc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(wP,"buildEventVersion2");async function vP(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&xP(e,o)){let i=await t.arrayBuffer();r=Fh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(vP,"getBodyResult");function xP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(xP,"matchesContentType");function RP(t,e=!1){if(!e)return t;let r=Pc(t),n=Uh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(RP,"getResourcePath");var PP=[502,503,504];async function Jr(t,e){if(PP.includes(t.status)){let r=K.getLogger(e),o=await t.clone().text(),i={};for(let[a,c]of t.headers)i[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Jr,"logBadGatewayResponses");var Ec;function Qt(t){if(Ec===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Ec=r}return t.log[Ec]}s(Qt,"getHandlerUserLogFunction");async function IP(t,e){R("handler.open-api");let r=P.instance.build.BUILD_ID,{buildAssetsUrl:n}=P.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new w("Open API Spec Handler must have 'openApiFilePath' specified");let a=SP(i);if(!a.isValid)throw new w(a.error);let c=`${n}/${r}${i.substring(1)}`,u=await z.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return D.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};P.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return Jr(d,e),d}s(IP,"openApiSpecHandler");var SP=s(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");async function kP(t,e){R("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new w("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}s(kP,"redirectHandler");async function TP(t){if(R("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new w("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,P.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${P.instance.authApiJWT}`),z.fetch(e,{method:t.method,headers:r,body:t.body})}s(TP,"zuploServiceProxy");function EP(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}s(EP,"join");async function CP(t,e){R("handler.url-forward");let r=Qt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i;if(P.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&R("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Kt(e),c=new URL(t.url),u=n.__rewriteFunction(t,a),l=EP(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=t.body;if(i==="follow"&&t.body)try{m=await t.arrayBuffer()}catch(b){throw new Error(`Failed to buffer request body for redirect handling: ${b}`)}let f=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${f.status} - ${f.statusText} in ${g}ms`),Jr(f,e),f}s(CP,"urlForwardHandler");var _P=s((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,i]of n.searchParams.entries())r.searchParams.append(o,i);return r.toString()},"addQuery");async function OP(t,e){R("handler.url-rewrite");let r=Qt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Kt(e),c=n.__rewriteFunction(t,a),u=o?_P(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual",zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Jr(d,e),d}s(OP,"urlRewriteHandler");function $P(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",n=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(n)}`),e.send(JSON.stringify(n))}),e.addEventListener("error",n=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(n)}`),t.send(JSON.stringify(n))}),t.addEventListener("message",n=>{e.send(n.data)}),e.addEventListener("message",n=>{t.send(n.data)})}s($P,"wireUpPassthrough");async function AP(t,e){R("handler.websocket");let r=e.route.handler.options,n=Qt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Kt(e),a=r.__rewriteFunction(t,i);if(n(`Attempting WebSocket connection to '${a}'`),P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let c=new WebSocket(a);await new Promise((d,p)=>{let m=s(()=>{g(),n("WebSocket connection established with upstream"),d()},"onOpen"),f=s(b=>{g(),n(`WebSocket connection error: ${b}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",f)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",f)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return $P(u,c,e),l}else{a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let u=await c.text(),l=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${u}'`;throw new Error(l)}return n(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(AP,"webSocketHandler");var Bh=s((t,e)=>{let r=e.route.handler?.options,n=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!n)throw new w("Developer portal URL is not configured.");if(r?.mode==="proxy"){let o=new URL(t.url);return o.hostname=new URL(n).hostname,z.fetch(o,{method:t.method,headers:t.headers,body:t.body})}else{let o=NP(t.url,n);return new Response(null,{status:301,headers:{location:o}})}},"legacyDevPortalHandler");function NP(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new w("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}s(NP,"getDevPortalRedirectUrl");var LP=Bh;var Cc=s((t,e)=>t.map((n,o)=>{let i;if(typeof n.module=="object"&&(i=n.module[n.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${n.export}`;throw new w(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),Vh=s(async(t,e,r,n,o,i)=>{let a=t.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");async function MP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=new WebSocket(e);await new Promise((a,c)=>{let u=s(()=>{d(),r("WebSocket connection established with upstream"),a()},"onOpen"),l=s(p=>{d(),r(`WebSocket connection error: ${p}`),c(new Error("Upstream open failed"))},"onErr"),d=s(()=>{n.removeEventListener("open",u),n.removeEventListener("error",l)},"cleanup");n.addEventListener("open",u),n.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:o,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:o,outgoingSocket:n,response:i}}s(MP,"getDenoClientAndServerSockets");async function DP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(n.status!==101||!n.webSocket){let u=await n.text(),l=`WebSocket connection error - ${n.status}: ${n.statusText}, content: '${u}'`;throw new Error(l)}let o=new WebSocketPair,[i,a]=Object.values(o);r(`WebSocket connected, received response ${n.status} - ${n.statusText}`),n.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{clientSocket:i,outgoingSocket:n.webSocket,serverSocket:a,response:c}}s(DP,"getCfClientAndServerSockets");function Jh(t,e,r,n,o,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{n.log.error(`WebSocket error: ${JSON.stringify(a)}, direction: ${i}`),e.send(JSON.stringify(a))}),t.addEventListener("message",a=>{try{let u=s(async l=>{let d=await Vh(l,t,e,r,n,o);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(n.log.error);n.waitUntil(u)}catch(c){n.log.error(c)}})}s(Jh,"wireUpListeners");async function UP(t,e){R("handler.websocket-pipeline");let r=e.route.handler.options,n=Qt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Kt(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?Cc(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?Cc(r.policies.outbound,"outbound"):[],l,d,p,m;if(P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let f=await MP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await DP(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Jh(l,d,t,e,c,"inbound"),Jh(d,l,t,e,u,"outbound"),m}s(UP,"webSocketPipelineHandler");Ze();er();er();function Sr({id:t,method:e,params:r}){return{jsonrpc:pt,id:t,method:e,params:r}}s(Sr,"newJSONRPCRequest");function Ct({id:t,result:e}){return{jsonrpc:pt,id:t,result:e}}s(Ct,"newJSONRPCReponse");function ke({id:t,code:e,message:r,data:n}){return{jsonrpc:pt,id:t,error:{code:e,message:r,data:n}}}s(ke,"newJSONRPCError");Ze();er();Zs();var Nw=y.object({jsonrpc:y.literal(pt),id:Aw,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();Mo();kr();Tr();var Do=s(t=>Mw.safeParse(t).success,"isJSONRPCRequest"),Uw=s(t=>Lw.safeParse(t).success,"isJSONRPCNotification"),on=s(t=>Dw.safeParse(t).success,"isJSONRPCResponse"),rr=s(t=>Nw.safeParse(t).success,"isJSONRPCError");var Uo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function nr(){return new Uo}s(nr,"createDefaultLogger");Ze();kr();Tr();Ze();var zw=y.object({experimental:y.optional(y.object({}).loose()),roots:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),sampling:y.optional(y.object({}).loose()),elicitation:y.optional(y.object({}).loose())}).loose(),jw=y.object({experimental:y.optional(y.object({}).loose()),logging:y.optional(y.object({}).loose()),completions:y.optional(y.object({}).loose()),prompts:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),resources:y.optional(y.object({subscribe:y.optional(y.boolean()),listChanged:y.optional(y.boolean())}).loose()),tools:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose())}).loose();Ze();sn();var nm=_t.extend({version:y.string()});var Zw=at.extend({method:y.literal("initialize"),params:st.extend({protocolVersion:y.string(),capabilities:zw,clientInfo:nm})}),GF=mt.extend({protocolVersion:y.string(),capabilities:jw,serverInfo:nm,instructions:y.optional(y.string())});Ze();Mo();kr();Tr();sn();qs();var jE=_t.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),ZE=_t.extend({description:y.optional(y.string()),arguments:y.optional(y.array(jE)),_meta:y.optional(y.object({}).loose())}),qE=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(sm(),Xo(im)),{ResourceLinkSchema:o}=(Fs(),Xo(pm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Vw=ir.extend({method:y.literal("prompts/list")}),hH=sr.extend({prompts:y.array(ZE)}),Jw=at.extend({method:y.literal("prompts/get"),params:st.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),yH=mt.extend({description:y.optional(y.string()),messages:y.array(qE)}),bH=tr.extend({method:y.literal("notifications/prompts/list_changed")});Fs();Ze();Mo();kr();Tr();sn();qs();var FE=y.object({title:y.optional(y.string()),readOnlyHint:y.optional(y.boolean()),destructiveHint:y.optional(y.boolean()),idempotentHint:y.optional(y.boolean()),openWorldHint:y.optional(y.boolean())}).loose(),HE=_t.extend({description:y.optional(y.string()),inputSchema:y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose(),outputSchema:y.optional(y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose()),annotations:y.optional(FE),_meta:y.optional(y.object({}).loose())}),kH=ir.extend({method:y.literal("tools/list")}),TH=sr.extend({tools:y.array(HE)}),Ww=at.extend({method:y.literal("tools/call"),params:st.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),EH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(sm(),Xo(im)),{ResourceLinkSchema:o}=(Fs(),Xo(pm));return mt.extend({content:y.array(y.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:y.optional(y.record(y.string(),y.unknown())),isError:y.optional(y.boolean())})}),CH=tr.extend({method:y.literal("notifications/tools/list_changed")});var zo="2025-06-18",mm="2025-03-26",fm="2024-11-05",gm="2024-10-07",hm=[zo,mm,fm,gm];var GE="MCP Server",BE="0.0.0",Hs=class{static{s(this,"MCPServer")}capabilities;tools=new Map;prompts=new Map;resources=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||GE,this.version=e.version||BE,this.instructions=e.instructions||void 0,this.logger=e.logger||nr(),this.capabilities={tools:{supported:!0,available:[]},prompts:{},resources:{},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(Do(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Uw(r))return await this.handleNotification(r),null;if(on(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),Do(r)){let o=ke({id:r.id,code:Se.InternalError,message:n instanceof Error?n.message:"Internal error"});return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:i=`Execute the ${r} tool`,outputSchema:a}=e,u={tool:{name:r,description:i,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,u),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}addPrompt(e){let{name:r,validator:n,generator:o,description:i}=e,a=n.jsonSchema,c;if(a.properties&&typeof a.properties=="object"){let d=new Set(a.required||[]);c=Object.entries(a.properties).map(([p,m])=>({name:p,description:m.description??`Prompt for ${p}`,required:d.has(p)}))}let l={prompt:{name:r,description:i,...c&&{arguments:c}},validator:n,generator:o};this.prompts.set(r,l)}removePrompt(e){return this.prompts.delete(e)}getPrompt(e){return this.prompts.get(e)?.prompt}getPromptDefinitions(){return Array.from(this.prompts.values()).map(e=>e.prompt)}addResource(e,r,n,o){if(typeof r=="string"){let a={type:"resource",resource:{name:e,uri:r,...n},reader:o};this.resources.set(e,a)}else{let a={type:"template",template:{name:e,uriTemplate:r.template,...n},reader:o};this.resources.set(e,a)}}removeResource(e){return this.resources.delete(e)}getResource(e){let r=this.resources.get(e);if(r)return r.type==="resource"?r.resource:void 0}getResourceTemplate(e){let r=this.resources.get(e);if(r)return r.type==="template"?r.template:void 0}getResourceDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="resource").map(e=>e.resource)}getResourceTemplateDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="template").map(e=>e.template)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);case"prompts/list":return this.handlePromptListRequest(e);case"prompts/get":return this.handlePromptGetRequest(e);case"resources/list":return this.handleResourceListRequest(e);case"resources/templates/list":return this.handleResourceTemplateListRequest(e);case"resources/read":return this.handleResourceReadRequest(e);default:return ke({id:e.id,code:Se.MethodNotFound,message:`Method "${e.method}" not found`})}}catch(r){return this.logger.error("Error handling request:",r),ke({id:e.id,code:Se.InternalError,message:r instanceof Error?r.message:"Internal error"})}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return Ct({id:e.id,result:{}})}handleInitialize(e){let r=Zw.safeParse(e);if(!r.success){let o=y.treeifyError(r.error),i=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${i}`,data:o})}let n=r.data.params.protocolVersion;switch(n){case zo:case mm:case fm:case gm:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return Ct({id:e.id,result:o})}default:return ke({id:e.id,code:Se.InvalidParams,message:`Unsupported protocol version: ${n} - supported versions: ${hm}`,data:{supportedVersions:hm}})}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return Ct({id:e.id,result:n})}async handleToolCallRequest(e){let r=Ww.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),ke({id:e.id,code:Se.InvalidRequest,message:`Invalid request ${r.error}`});let n=r.data,o=n.params.name,i=this.tools.get(o);if(!i)return ke({id:e.id,code:Se.InvalidParams,message:`Tool "${o}" not found`});let a=n.params.arguments??{},c=i.validator.parse(a);if(!c.success)return ke({id:e.id,code:Se.InvalidParams,message:c.errorMessage?`Invalid arguments for tool '${o}': ${c.errorMessage}`:`Invalid arguments for tool '${o}'`,data:c.errorData});try{let u=c.data,l=await i.handler(u);return Ct({id:e.id,result:l})}catch(u){return this.logger.error(`Error executing tool "${o}":`,u),ke({id:e.id,code:Se.InternalError,message:u instanceof Error?u.message:"Tool execution error"})}}async handlePromptListRequest(e){let r=Vw.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={prompts:Array.from(this.prompts.values()).map(i=>i.prompt)};return Ct({id:e.id,result:o})}async handlePromptGetRequest(e){let r=Jw.safeParse(e);if(!r.success){let c=y.treeifyError(r.error),u=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${u}`,data:c})}let n=r.data.params.name,o=this.prompts.get(n);if(!o)return ke({id:e.id,code:Se.InvalidParams,message:`Prompt "${n}" not found`});let i=r.data.params.arguments??{},a=o.validator.parse(i);if(!a.success)return ke({id:e.id,code:Se.InvalidParams,message:a.errorMessage?`Invalid arguments for prompt '${n}': ${a.errorMessage}`:`Invalid arguments for prompt '${n}'`,data:a.errorData});try{let c=a.data,u=await o.generator(c),l={...o.prompt.description&&{description:o.prompt.description},messages:u};return Ct({id:e.id,result:l})}catch(c){return this.logger.error(`Error generating prompt "${n}":`,c),ke({id:e.id,code:Se.InternalError,message:c instanceof Error?c.message:"Prompt generation error"})}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}async handleResourceListRequest(e){let r=um.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resources:Array.from(this.resources.values()).filter(i=>i.type==="resource").map(i=>i.resource)};return Ct({id:e.id,result:o})}async handleResourceTemplateListRequest(e){let r=lm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resourceTemplates:Array.from(this.resources.values()).filter(i=>i.type==="template").map(i=>i.template)};return Ct({id:e.id,result:o})}async handleResourceReadRequest(e){let r=dm.safeParse(e);if(!r.success){let a=y.treeifyError(r.error),c=y.prettifyError(r.error);return ke({id:e.id,code:Se.InvalidParams,message:`Invalid request parameters: ${c}`,data:a})}let n=r.data.params.uri;function o(a,c){let u=c.replace(/\{[^}]+\}/g,"([^/]+)");return new RegExp(`^${u}$`).test(a)}s(o,"matchesTemplate");let i=Array.from(this.resources.values()).find(a=>a.type==="resource"&&a.resource.uri===n||a.type==="template"&&o(n,a.template.uriTemplate));if(!i)return ke({id:e.id,code:Se.ResourceNotFound,message:`Resource not found: ${n}`,data:{uri:n}});try{let a=await i.reader(n);return Ct({id:e.id,result:a})}catch(a){return this.logger.error(`Error reading resource "${n}":`,a),ke({id:e.id,code:Se.ResourceNotFound,message:a instanceof Error?a.message:"Resource not found",data:{uri:n}})}}};var ar=class{static{s(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};er();var Gs=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;headers;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;setHeaders(e){this.headers={...this.headers,...e}}constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.headers={"Content-Type":"application/json",...e.headers},this.logger=e.logger||nr(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(on(e)){for(let[r,n]of this.sessions.entries())for(let[o,i]of n.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),Do(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify(ke({code:-32e3,message:"Transport not connected",id:null})),{status:503,headers:this.headers});if(!this.messageHandler)return new Response(JSON.stringify(ke({code:-32e3,message:"No message handler registered",id:null})),{status:500,headers:this.headers});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){return this.logger.error("Error handling request:",n),new Response(JSON.stringify(ke({code:Se.InternalError,message:"Internal server error",id:null})),{status:400,headers:this.headers})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify(ke({code:Se.InvalidRequest,message:"Not Acceptable: Client must accept application/json and text/event-stream",id:null})),{status:406,headers:this.headers});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify(ke({code:Se.ParseError,message:"Parse error: received invalid JSON",id:null})),{status:400,headers:this.headers});let i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=r;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let p of i)await this.messageHandler?.(p);return new Response(null,{status:202,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}if(!this.enableStreaming){let p=[];for(let f of i)if(this.isRequest(f)){let g=await this.messageHandler?.(f);g&&p.push(g)}else await this.messageHandler?.(f);let m=p.length===1?p[0]:p;return new Response(JSON.stringify(m),{status:200,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let p of i)if(this.isRequest(p)){this.streams.get(l)?.pendingRequests.add(p.id);let m=this.messageHandler?.(p);d.push(m)}else await this.messageHandler?.(p);return new Response(u.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}catch{return new Response(JSON.stringify(ke({code:Se.InternalError,message:"Internal server error",id:null})),{status:500,headers:this.headers})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:this.headers});if(this.options.enableSessions&&!r)return new Response(JSON.stringify(ke({code:Se.InvalidRequest,message:"Session ID required",id:null})),{status:400,headers:this.headers});let{stream:o,streamId:i}=this.createStream(r),a=e.headers.get("Last-Event-ID");return a&&r&&await this.replayMessages(r,i,a),new Response(o.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...r&&{"Mcp-Session-Id":r.id}}})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,i]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let i=`id: ${n}
|
|
88
88
|
data: ${o}
|
|
89
89
|
|
|
90
90
|
`;await e.writer.write(new TextEncoder().encode(i))}catch(n){this.logger.warn("Error sending to stream:",n)}}async closeStream(e,r){let n=this.sessions.get(e);if(!n)return;let o=n.streams.get(r);if(o){try{await o.writer.close()}catch(i){this.logger.warn("Error closing stream:",i)}n.streams.delete(r),this.streams.delete(r)}}createSession(e){let r={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,r),r}createStream(e){let r=new TransformStream,n=r.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),i={id:o,writer:n,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,i),e&&(e.streams.set(o,i),e.lastActivity=Date.now()),{stream:r,streamId:o}}async replayMessages(e,r,n){for(let o of e.streams.values()){if(o.id===r)continue;let i=Number.parseInt(n,10);if(Number.isNaN(i))continue;let a=o.messages.slice(i),c=this.streams.get(r);if(c&&a.length>0)for(let u of a)await this.sendToStream(c,u)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[r,n]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-n.lastActivity>o){for(let[i,a]of n.streams.entries()){try{a.writer.close().catch(c=>this.logger.warn("Error closing stream:",c))}catch(c){this.logger.warn("Error closing stream:",c)}this.streams.delete(i)}this.sessions.delete(r)}}},6e4)}async extractJSONRPC(e){try{let n=await e.clone().text();if(!n)throw new Error("Empty request body");return JSON.parse(n)}catch(r){throw new Error(`Failed to parse JSON-RPC message: ${r}`)}}validateOrigin(e){let r=e.headers.get("Origin");if(r&&!this.isValidOrigin(r))throw new Error("Invalid origin")}isValidOrigin(e){return!0}isRequest(e){return e!==null&&typeof e=="object"&&"jsonrpc"in e&&e.jsonrpc==="2.0"&&"method"in e&&"id"in e&&e.id!==null&&e.id!==void 0}generateFallbackUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}};function Bs(t){let e={descriptions:!0,specifiedByUrl:!1,directiveIsRepeatable:!1,schemaDescription:!1,inputValueDeprecation:!1,oneOf:!1,...t},r=e.descriptions?"description":"",n=e.specifiedByUrl?"specifiedByURL":"",o=e.directiveIsRepeatable?"isRepeatable":"",i=e.schemaDescription?r:"";function a(u){return e.inputValueDeprecation?u:""}s(a,"inputDeprecation");let c=e.oneOf?"isOneOf":"";return`
|