@zuplo/graphql 5.1533.0 → 5.1535.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.minified.js +1 -1
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -62,7 +62,7 @@ ${r}
|
|
|
62
62
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
63
63
|
`)}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 vy.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=sd(await Ey(this.body||""))}return e}};fn.AwsV4Signer=Us;async function yi(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?ad.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,ad.encode(e))}o(yi,"hmac");async function Ey(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?ad.encode(t):t)}o(Ey,"hash");function sd(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}o(sd,"buf2hex");function wy(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}o(wy,"encodeRfc3986");function lI(t,e){let{hostname:r,pathname:n}=t,i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(i||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?s="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in by?[by[s],a]:[s,a]}o(lI,"guessServiceRegion")});var Ty=g(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.convertStringToUtf8Array=vt.convertUtf8ArrayToString=vt.base64Encode=vt.base64Decode=void 0;function dI(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}o(dI,"b64ToUint6");function pI(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,i=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(i),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=dI(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<i;)s[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return s}o(pI,"base64Decode");vt.base64Decode=pI;function Ms(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}o(Ms,"uint6ToB64");function hI(t){let e=2,r="",n=t.length,i=0;for(let s=0;s<n;s++)e=s%3,i|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(Ms(i>>>18&63),Ms(i>>>12&63),Ms(i>>>6&63),Ms(i&63)),i=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}o(hI,"base64Encode");vt.base64Encode=hI;function fI(t){let e="",r,n=t.length;for(let i=0;i<n;i++)r=t[i],e+=String.fromCodePoint(r>251&&r<254&&i+5<n?(r-252)*1073741824+(t[++i]-128<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>247&&r<252&&i+4<n?(r-248<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>239&&r<248&&i+3<n?(r-240<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>223&&r<240&&i+2<n?(r-224<<12)+(t[++i]-128<<6)+t[++i]-128:r>191&&r<224&&i+1<n?(r-192<<6)+t[++i]-128:r);return e}o(fI,"convertUtf8ArrayToString");vt.convertUtf8ArrayToString=fI;function mI(t){let e,r=t.length,n=0;for(let c=0;c<r;c++)e=t.codePointAt(c),e>=65536&&c++,n+=e<128?1:e<2048?2:e<65536?3:e<2097152?4:e<67108864?5:6;let i=new Uint8Array(n),s=0,a=0;for(;s<n;)e=t.codePointAt(a),e<128?i[s++]=e:e<2048?(i[s++]=192+(e>>>6),i[s++]=128+(e&63)):e<65536?(i[s++]=224+(e>>>12),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63)):e<2097152?(i[s++]=240+(e>>>18),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):e<67108864?(i[s++]=248+(e>>>24),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):(i[s++]=252+(e>>>30),i[s++]=128+(e>>>24&63),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++),a++;return i}o(mI,"convertStringToUtf8Array");vt.convertStringToUtf8Array=mI});var Sy=g(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.toCLFDate=void 0;function mn(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}o(mn,"numberToString");function yI(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",i=mn(Math.floor(r/60)),s=mn(r%60);return`${n}${i}${s}`}o(yI,"getCLFOffset");function gI(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=mn(t.getDate()),n=e[t.getMonth()],i=t.getFullYear(),s=mn(t.getHours()),a=mn(t.getMinutes()),c=mn(t.getSeconds()),u=yI(t);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(gI,"toCLFDate");ks.toCLFDate=gI});var Ny=g(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.getResponse=sr.awsLambdaHandler=sr.AwsLambdaHandlerExtensions=void 0;var _I=Er(),Iy=_y(),gi=D(),bI=Ot(),EI=ud(),Py=Ty(),Ry=Sy(),Ay=(0,_I.debug)("zuplo:runtime"),wI="X-Amzn-Trace-Id",vI="x-amzn-errortype",Oy=[],TI=o(async(t,e,r)=>{let n=r;for await(let i of Oy)n=await i(t,e,r);return n},"onSendingAwsLambdaEvent"),Be=class extends gi.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(wI)??void 0,this.errorType=r.get(vI)??void 0}};sr.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:t=>{Oy.push(t)}};async function SI(t,e){let{accessKeyId:r,secretAccessKey:n,region:i,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new gi.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new gi.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new gi.ConfigurationError("region is not set in the handler options");if(!s)throw new gi.ConfigurationError("functionName is not set in the handler options");let l=new EI.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Ay(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await PI(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,y;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?y=AI(t,e):y=await II(t,e,{useAwsResourcePathStyle:c}),Ay("Calling onSendingAwsLambdaEvent hook");let v=await TI(t,e,y);v.body=p,v.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(v)});try{return xy(T)}catch(I){if(I instanceof Be){let k=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&I.traceId?{AMZN_TRACE_ID_HEADER:I.traceId}:void 0;return bI.HttpProblems.internalServerError(t,e,void 0,k)}throw I}}o(SI,"awsLambdaHandler");sr.awsLambdaHandler=SI;async function xy(t){let e;try{e=await t.json()}catch{throw new Be("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Be(e.message,t.headers):new Be(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Be(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Be(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[i,s]of Object.entries(e.headers))r.set(i,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Be(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Be(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Be("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new Be("Response was set to base64 encoded but body was not a string",t.headers);n=(0,Py.base64Decode)(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Be(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let i=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(i).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}o(xy,"getResponse");sr.getResponse=xy;async function II(t,e,{useAwsResourcePathStyle:r}){let n={},i={};t.headers.forEach((l,d)=>{n[d]=l,i[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:i,queryStringParameters:s,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:(0,Ry.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:OI(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}o(II,"buildEventVersion1");function AI(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});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:(0,Ry.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}o(AI,"buildEventVersion2");async function PI(t,{binaryMediaTypes:e}){let r,n=!1,i=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&i&&RI(e,i)){let s=await t.arrayBuffer();r=(0,Py.base64Encode)(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}o(PI,"getBodyResult");function RI(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(RI,"matchesContentType");function OI(t,e=!1){if(!e)return t;let r=(0,Iy.parse)(t),n=(0,Iy.compile)(t),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(OI,"getResourcePath")});var gn=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.getHandlerUserLogFunction=yn.logBadGatewayResponses=void 0;var xI=Ge(),NI=te(),CI=[502,503,504];async function LI(t,e){if(CI.includes(t.status)){let r=xI.SystemLogMap.getLogger(e),i=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:i,headers:s})}}o(LI,"logBadGatewayResponses");yn.logBadGatewayResponses=LI;var ld;function DI(t){if(ld===void 0){let r=NI.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),ld=r}return t.log[ld]}o(DI,"getHandlerUserLogFunction");yn.getHandlerUserLogFunction=DI});var Ly=g(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.openApiSpecHandler=void 0;var Cy=D(),UI=ve(),dd=te(),MI=gn();async function kI(t,e){let r=dd.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=dd.Environment.instance,i=e.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new Cy.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=FI(s);if(!a.isValid)throw new Cy.ConfigurationError(a.error);let c;dd.Environment.instance.isLocalDevelopment?c=`${n}/${s.substring(1)}`:c=`${n}/${r}${s.substring(1)}`;let u=await fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return UI.HttpProblems.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json"},status:u.status,statusText:u.statusText});return(0,MI.logBadGatewayResponses)(l,e),l}o(kI,"openApiSpecHandler");Fs.openApiSpecHandler=kI;var FI=o(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")});var Dy=g(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.redirectHandler=void 0;var HI=D();async function qI(t,e){let r=e.route.handler.options;if(!r.location)throw new HI.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(qI,"redirectHandler");Hs.redirectHandler=qI});var My=g(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.urlForwardHandler=void 0;var $I=D(),Uy=gn();function jI(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}`}o(jI,"join");async function VI(t,e){let r=(0,Uy.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1;if(!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new $I.ConfigurationError("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),c=n.__rewriteFunction(t,s),u=jI(c,a.pathname),l=i?`${u}${a.search}`:u.toString(),d=Date.now();r(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),(0,Uy.logBadGatewayResponses)(p,e),p}o(VI,"urlForwardHandler");qs.urlForwardHandler=VI});var Fy=g($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.urlRewriteHandler=void 0;var GI=D(),ky=gn(),BI=o((t,e)=>{let r=new URL(t),n=new URL(e);for(let[i,s]of n.searchParams.entries())r.searchParams.append(i,s);return r.toString()},"addQuery");async function KI(t,e){let r=(0,ky.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new GI.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=i?BI(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:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),(0,ky.logBadGatewayResponses)(d,e),d}o(KI,"urlRewriteHandler");$s.urlRewriteHandler=KI});var qy=g(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.webSocketHandler=void 0;var Hy=D(),JI=ed(),zI=Ot(),WI=te(),QI=gn();async function YI(t,e){let r=WI.Environment.instance,n=e.route.handler.options,i=(0,QI.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new Hy.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return zI.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Hy.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno){let p=new Headers(t.headers);if(c.startsWith("service:")){let f=await(0,JI.externalServiceTunnelConfig)(c),y=new URL(c);c=new URL(`${f.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let T in f.tunnelHeaders)p.set(T,f.tunnelHeaders[T])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let f=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${f}`}}catch{}let m=JSON.stringify({url:c});return new Response(m,{headers:p})}c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-u;return i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}o(YI,"webSocketHandler");js.webSocketHandler=YI});var $y=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.webSocketPolicyProcessor=_n.getWebSocketPolicyFunctions=void 0;var ZI=D(),XI=o((t,e)=>t.map((n,i)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${i+1}, export name: ${n.export}`;throw new ZI.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");_n.getWebSocketPolicyFunctions=XI;var eA=o(async(t,e,r,n,i,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,r,e,n,i),a===void 0)return}}return a},"webSocketPolicyProcessor");_n.webSocketPolicyProcessor=eA});var Vy=g(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.webSocketPipelineHandler=void 0;var pd=D(),tA=Ot(),rA=te(),nA=gn(),hd=$y();function jy(t,e,r,n,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{o(async c=>{let u=await(0,hd.webSocketPolicyProcessor)(c,t,e,r,n,i);u!==void 0&&e.send(u)},"innerPipeline")(s).catch(n.log.error)}catch(a){n.log.error(a)}})}o(jy,"wireUpListeners");async function iA(t,e){let r=rA.Environment.instance,n=e.route.handler.options,i=(0,nA.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new pd.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return tA.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new pd.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno)throw new pd.ConfigurationError("Websocket pipeline handler is currently not supported on working-copy environments");c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let I=await l.text(),k=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${I}'`;throw new Error(k)}let d=new WebSocketPair,[p,m]=Object.values(d),f=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${f}ms`);let y=l.webSocket;y.accept(),m.accept();let v=n.policies&&n.policies.inbound?(0,hd.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],T=n.policies&&n.policies.outbound?(0,hd.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return jy(m,y,t,e,v),jy(y,m,t,e,T),new Response(null,{status:101,webSocket:p})}o(iA,"webSocketPipelineHandler");Vs.webSocketPipelineHandler=iA});var Gy=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.DynaTraceLoggingPlugin=void 0;var oA=we(),fd=te(),sA=Ar(),aA=Nt(),cA=mt(),md=class extends aA.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new yd(this.options)}};Gs.DynaTraceLoggingPlugin=md;var yd=class{static{o(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#n=fd.Environment.instance.loggingEnvironmentType,this.#i=fd.Environment.instance.loggingEnvironmentStage,this.#r=fd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,cA.stringifyNonString)((0,sA.serializeError)(n)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#r,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new oA.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var By=g(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.LokiLoggingPlugin=void 0;var uA=we(),gd=te(),lA=Ar(),dA=Nt(),pA=mt(),_d=class extends dA.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ed(this.options)}};Bs.LokiLoggingPlugin=_d;var bd=class{static{o(this,"LokiStream")}constructor(e,r,n,i,s){this.level=e,this.environment=r,this.environmentType=n,this.environmentStage=i,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function hA(t,e){return btoa(`${t}:${e}`)}o(hA,"createBasicDigest");var Ed=class{static{o(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=hA(e.username,e.password),this.#n=gd.Environment.instance.loggingEnvironmentType,this.#i=gd.Environment.instance.loggingEnvironmentStage,this.#r=gd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){let n=new bd(e.level,this.#r,this.#n,this.#i,e.requestId);e.messages.forEach(i=>{let s={stream:n,message:(0,pA.stringifyNonString)((0,lA.serializeError)(i)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=e=>{let r={streams:[]};return e.forEach(n=>{let i=r.streams.find(s=>s.stream.equals(n.stream));i||(i={stream:n.stream,values:[]},r.streams.push(i)),i.values.push([n.nanoSecondEpoch,n.message])}),r};#s=async e=>{if(e.length===0)return;let r=this.#o(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new uA.BatchDispatch("loki-log-transport",10,this.#s)}});var Ky=g(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.SumoLogicLoggingPlugin=void 0;var fA=we(),wd=te(),mA=Ar(),yA=Nt(),gA=mt(),vd=class extends yA.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Td(this.options)}};Ks.SumoLogicLoggingPlugin=vd;var Td=class{static{o(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#i=e.category,this.#o=e.name,this.#r=wd.Environment.instance.loggingEnvironmentType,this.#n=wd.Environment.instance.loggingEnvironmentStage,this.#t=wd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,gA.stringifyNonString)((0,mA.serializeError)(n)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#r,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let r=e.map(i=>JSON.stringify(i)).join(`
|
|
64
64
|
`),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#o&&n.set("X-Sumo-Name",this.#o),this.#i&&n.set("X-Sumo-Category",this.#i),await fetch(this.#e,{method:"POST",body:r,headers:n})};batcher=new fA.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var zy=g(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.VMWareLogInsightTransport=bn.VMWareLogInsightLoggingPlugin=void 0;var _A=D(),bA=we(),Sd=te(),EA=Nt(),Jy=mt(),wA="d3a5b78f-8236-48f5-b1df-4fe269d41172",Id=class extends EA.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Js(this.options)}};bn.VMWareLogInsightLoggingPlugin=Id;var Js=class{static{o(this,"VMWareLogInsightTransport")}constructor(e){let r;try{r=new URL(e.url)}catch{throw new _A.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.origin,this.#r=Sd.Environment.instance.loggingEnvironmentType,this.#n=Sd.Environment.instance.loggingEnvironmentStage,this.#t=Sd.Environment.instance.deploymentName,this.#i=e.onMessageSending,e.fields&&(this.#o=Object.entries(e.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;async log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=(0,Jy.messagesToMultilineText)(e.messages),i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#n},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&i.fields.push({name:"request_ray_id",content:e.rayId}),this.#t&&i.fields.push({name:"environment",content:this.#t}),this.#o&&i.fields.push(...this.#o),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,Jy.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#i&&(i=this.#i(i)),i}#s=async e=>{if(e.length===0)return;let r=await fetch(`${this.#e}/api/v1/events/ingest/${wA}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(r.status!==200)try{let n=await r.text();console.error("Error logging to Log Insight",n)}catch(n){console.error(n)}};batcher=new bA.BatchDispatch("vmware-log-insights-log-transport",10,this.#s)};bn.VMWareLogInsightTransport=Js});var Qy=g(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.AWSLogTransport=En.AWSLoggingPlugin=void 0;var vA=we(),Wy=te(),TA=Ar(),SA=Nt(),IA=mt(),AA=ud(),Ad=class extends SA.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new zs(this.options)}};En.AWSLoggingPlugin=Ad;var zs=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new vA.BatchDispatch("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:r,logGroupName:n,secretAccessKey:i,region:s}){this.awsClient=new AA.AwsClient({accessKeyId:e,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=Wy.Environment.instance.loggingEnvironmentType,this.environment=Wy.Environment.instance.deploymentName}async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,IA.stringifyNonString)((0,TA.serializeError)(n)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}};En.AWSLogTransport=zs});var Yy=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.AWSLoggingPlugin=Oe.VMWareLogInsightLoggingPlugin=Oe.SumoLogicLoggingPlugin=Oe.LokiLoggingPlugin=Oe.GoogleCloudLoggingPlugin=Oe.DynaTraceLoggingPlugin=Oe.DataDogLoggingPlugin=void 0;var PA=Ul();Object.defineProperty(Oe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return PA.DataDogLoggingPlugin}});var RA=Gy();Object.defineProperty(Oe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return RA.DynaTraceLoggingPlugin}});var OA=_s();Object.defineProperty(Oe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return OA.GoogleCloudLoggingPlugin}});var xA=By();Object.defineProperty(Oe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return xA.LokiLoggingPlugin}});var NA=Ky();Object.defineProperty(Oe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return NA.SumoLogicLoggingPlugin}});var CA=zy();Object.defineProperty(Oe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return CA.VMWareLogInsightLoggingPlugin}});var LA=Qy();Object.defineProperty(Oe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return LA.AWSLoggingPlugin}})});var Zy=g(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.DataDogMetricsError=ar.DataDogMetricsTransport=ar.DataDogMetricsPlugin=void 0;var DA=Ge(),UA=we(),MA=po(),Pd=new WeakMap,kA={tags:[]},Rd=class extends MA.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ws(this.options)}static setContext(e,r){let n=Pd.get(e);n||(n=kA);let i=Object.assign({...n},r);Pd.set(e,i)}};ar.DataDogMetricsPlugin=Rd;var Ws=class{static{o(this,"DataDogMetricsTransport")}#e;#t;#r;#n;#i;#o=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#n=e.tags??[]}pushMetrics(e,r){this.#o===void 0&&(this.#o=new UA.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,DA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),i=this.#n.concat(Pd.get(r)?.tags??[]);if(this.#i.country&&i.push(`country:${e.country}`),this.#i.httpMethod&&i.push(`httpMethod:${e.method}`),this.#i.statusCode&&i.push(`statusCode:${e.statusCode}`),this.#i.path){let s=e.systemRouteName||e.routePath;i.push(`path:${s}`)}this.#r.latency&&this.#o.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:i}),this.#r.requestContentLength&&e.requestContentLength&&this.#o.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:i}),this.#r.responseContentLength&&e.responseContentLength&&this.#o.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:i}),r.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=JSON.stringify({series:e}),n=await fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!n.ok)throw new Qs(await n.text())}};ar.DataDogMetricsTransport=Ws;var Qs=class t extends Error{static{o(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};ar.DataDogMetricsError=Qs});var Xy=g(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.DynaTraceMetricsError=cr.DynaTraceMetricsTransport=cr.DynatraceMetricsPlugin=void 0;var FA=Ge(),HA=we(),qA=po(),Od=new WeakMap,$A={dimensions:[]},xd=class extends qA.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ys(this.options)}static setContext(e,r){let n=Od.get(e);n||(n=$A);let i=Object.assign({...n},r);Od.set(e,i)}};cr.DynatraceMetricsPlugin=xd;var Ys=class{static{o(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#r;#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.#r=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#n===void 0&&(this.#n=new HA.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,FA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),i=this.dimensions.concat(Od.get(r)?.dimensions??[]);if(this.#r.country&&i.push(`country="${e.country}"`),this.#r.httpMethod&&i.push(`http_method="${e.method}"`),this.#r.statusCode&&i.push(`status_code="${e.statusCode}"`),this.#r.path){let a=e.systemRouteName||e.routePath;i.push(`path="${a}"`)}let s=i.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${n}`),r.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=e.join(`
|
|
65
|
-
`),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new Zs(await n.text())}};cr.DynaTraceMetricsTransport=Ys;var Zs=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};cr.DynaTraceMetricsError=Zs});var eg=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.DynatraceMetricsPlugin=wn.DataDogMetricsPlugin=void 0;var jA=Zy();Object.defineProperty(wn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return jA.DataDogMetricsPlugin}});var VA=Xy();Object.defineProperty(wn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return VA.DynatraceMetricsPlugin}})});var tg=g(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.AuditLogDataStaxProvider=void 0;var Nd=class{static{o(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};Xs.AuditLogDataStaxProvider=Nd});var ng=g(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.AuditLogPlugin=void 0;var GA=Rt(),BA=we(),Cd=class extends GA.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Ld(e,this.#e,this.#t)}};ea.AuditLogPlugin=Cd;var rg=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),KA={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ld=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...KA};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,e.addRequestHook(this.#o),this.#r=new BA.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async e=>{await this.#t.writeLogBatch(e)};#i=async(e,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?rg(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?rg(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let i=new Date,s=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var ta=g(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.getValueFromRequestUser=vn.statusCodesStringToNumberArray=void 0;var ig=D(),og=new Map;function JA(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=og.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return og.set(t,n),n}o(JA,"statusCodesStringToNumberArray");vn.statusCodesStringToNumberArray=JA;function zA(t,e,r){if(!e.startsWith("."))throw new ig.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new ig.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(zA,"getValueFromRequestUser");vn.getValueFromRequestUser=zA});var lg=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.AmberfloMeteringInboundPolicy=Tn.AmberfloMeteringPolicy=void 0;var sg=D(),WA=we(),ag=ta(),ug=new WeakMap,cg={},Dd=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){ug.set(e,r)}};Tn.AmberfloMeteringPolicy=Dd;async function QA(t,e,r,n){if(!r.statusCodes)throw new sg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,ag.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=ug.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new sg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,ag.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},m=cg[r.apiKey];if(!m){let f=r.apiKey,y=t.headers.get("zm-test-id")??"";m=new WA.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",I=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});I.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${I.status}: ${await I.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),cg[f]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}o(QA,"AmberfloMeteringInboundPolicy");Tn.AmberfloMeteringInboundPolicy=QA});var ur=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.getPolicyCacheName=void 0;function YA(t){return`zuplo-policy-${t}`}o(YA,"getPolicyCacheName");ra.getPolicyCacheName=YA});var fg=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.ApiAuthKeyInboundPolicy=Sn.ApiKeyInboundPolicy=void 0;var ZA=ur(),XA=_r(),dg=Xl(),Ud=D(),eP=Ot(),Md=Ge(),kd=te(),tP=ys(),pg="key-metadata-cache-type";function rP(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(rP,"getKeyValue");async function hg(t,e,r,n){if(!r.bucketName)if(dg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=dg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Ud.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Ud.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:eP.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=rP(a,i);if(!c||c==="")return s("No key present");let u=await nP(c),l=new XA.MemoryZoneReadThroughCache((0,ZA.getPolicyCacheName)(n),{logger:Md.SystemLogMap.getLogger(e)}),d=await l.get(u);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==pg&&Md.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${d.typeId}'`,d),s("Authorization Failed");let p={key:c},m=await(0,tP.fetchRetry)({retryDelayMs:5,retries:2,logger:Md.SystemLogMap.getLogger(e)},`${kd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":kd.Environment.instance.deploymentName??"unknown","User-Agent":kd.Environment.instance.systemUserAgent},body:JSON.stringify(p)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),T=JSON.parse(v);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new Ud.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${m.status}`)}let f=await m.json(),y={isValid:!0,typeId:pg,user:{sub:f.name,data:f.metadata}};return t.user=y.user,l.put(u,y,i.cacheTtlSeconds),t}o(hg,"ApiKeyInboundPolicy");Sn.ApiKeyInboundPolicy=hg;async function nP(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(nP,"hashValue");Sn.ApiAuthKeyInboundPolicy=hg});var Mt=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.OpenIdJwtInboundPolicy=void 0;var Hd=(fs(),Bi(hs)),qd=D(),iP=ve(),Fd={},oP=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new qd.ConfigurationError("Invalid State - jwkUrl not set");Fd[e.jwkUrl]||(Fd[e.jwkUrl]=(0,Hd.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Hd.jwtVerify)(t,Fd[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),sP=o(async(t,e)=>{let r;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Hd.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),aP=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(m=>iP.HttpProblems.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?oP:sP,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=i.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(f){let y=new URL(t.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,f):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,f),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");na.OpenIdJwtInboundPolicy=aP});var mg=g(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.Auth0JwtInboundPolicy=void 0;var cP=Mt(),uP=o(async(t,e,r,n)=>(0,cP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");ia.Auth0JwtInboundPolicy=uP});var yg=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.BasicAuthInboundPolicy=void 0;var lP=ve(),dP=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>lP.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===f);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");oa.BasicAuthInboundPolicy=dP});var gg=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.CachingInboundPolicy=void 0;var pP=ur(),hP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function fP(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(fP,"digestMessage");var mP=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await fP(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function yP(t,e,r,n){let i=await caches.open(`${(0,pP.getPolicyCacheName)(n)}-${r.cacheId??""}`),s=r?.cacheHttpMethods?.map(u=>u.toUpperCase())??["GET"],a=await mP(t,r),c=await i.match(a);return c||(e.addEventListener("responseSent",u=>{try{let l=r.statusCodes??[200,206,301,302,303,404,410],d=u.response.clone();if(!l.includes(d.status)||!s.includes(t.method.toUpperCase()))return;let p=r?.expirationSecondsTtl??60,m=new Response(d.body,d);hP.forEach(f=>m.headers.delete(f)),m.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(i.put(a,m))}catch(l){e.log.error(`Error in caching-inbound-policy '${n}': "${l.message}"`,l)}}),t)}o(yP,"CachingInboundPolicy");sa.CachingInboundPolicy=yP});var _g=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.ChangeMethodInboundPolicy=void 0;var gP=D(),_P=Wn(),bP=o(async(t,e,r,n)=>{if(!r.method)throw new gP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new _P.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");aa.ChangeMethodInboundPolicy=bP});var bg=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.ClearHeadersInboundPolicy=void 0;var EP=ke(),wP=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new EP.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");ca.ClearHeadersInboundPolicy=wP});var Eg=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.ClearHeadersOutboundPolicy=void 0;var vP=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");ua.ClearHeadersOutboundPolicy=vP});var wg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.ClerkJwtInboundPolicy=void 0;var TP=Mt(),SP=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,TP.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");la.ClerkJwtInboundPolicy=SP});var Tg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.CognitoJwtInboundPolicy=void 0;var vg=D(),IP=Mt(),AP=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new vg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new vg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,IP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");da.CognitoJwtInboundPolicy=AP});var Ig=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.CompositeInboundPolicy=void 0;var PP=D(),RP=un(),Sg=Qn(),OP=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new PP.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=RP.Gateway.instance,s=(0,Sg.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Sg.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");pa.CompositeInboundPolicy=OP});var lr=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.optionValidator=void 0;var _i=D();function xP(t,e){let r=o((s,a,c)=>{let u=t[s];if(!(c&&u===void 0)){if(u===void 0)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(xP,"optionValidator");ha.optionValidator=xP});var Ag=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.FirebaseJwtInboundPolicy=void 0;var NP=lr(),CP=Mt(),LP=o(async(t,e,r,n)=>((0,NP.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,CP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");fa.FirebaseJwtInboundPolicy=LP});var Pg=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.FormDataToJsonInboundPolicy=void 0;var DP=ke(),UP=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new DP.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");ma.FormDataToJsonInboundPolicy=UP});var Rg=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.GeoFilterInboundPolicy=void 0;var MP=D(),kP=ve(),In="__unknown__",FP=o(async(t,e,r,n)=>{let i={allow:{countries:Pn(r.allow?.countries,"allow.countries",n),regionCodes:Pn(r.allow?.regionCodes,"allow.regionCode",n),asns:Pn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Pn(r.block?.countries,"block.countries",n),regionCodes:Pn(r.block?.regionCodes,"block.regionCode",n),asns:Pn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??In,a=e.incomingRequestProperties.regionCode?.toLowerCase()??In,c=e.incomingRequestProperties.asn?.toString()??In,u=i.ignoreUnknown&&s===In,l=i.ignoreUnknown&&a===In,d=i.ignoreUnknown&&c===In,p=i.allow.countries,m=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||m.length>0&&!m.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return An(t,e,n,s,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?An(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");ya.GeoFilterInboundPolicy=FP;function An(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),kP.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(An,"blockedResponse");function Pn(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new MP.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(Pn,"toLowerStringArray")});var Og=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.JWTScopeValidationInboundPolicy=void 0;var HP=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");ga.JWTScopeValidationInboundPolicy=HP});var Ng=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.MockApiInboundPolicy=void 0;var qP=ve(),$P=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return $d(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return $d(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return xg(a[c])}else return a.length>0?xg(a[0]):$d(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");_a.MockApiInboundPolicy=$P;function xg(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.append("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(xg,"generateResponse");var $d=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return qP.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Mg=g(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.MoesifInboundPolicy=Rn.setMoesifContext=void 0;var jP=D(),VP=we(),GP="Incoming",BP={logRequestBody:!0,logResponseBody:!0};function Cg(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(Cg,"headersToObject");function Lg(){return new Date().toISOString()}o(Lg,"timestamp");var jd=new WeakMap,KP={};function JP(t,e){let r=jd.get(t);r||(r=KP);let n=Object.assign({...r},e);jd.set(t,n)}o(JP,"setMoesifContext");Rn.setMoesifContext=JP;async function Dg(t,e){let r=t.headers.get("content-type"),n=t.clone();if(r&&r.indexOf("json")!==0)try{return await n.json()}catch(s){e.log.error(s)}let i=await n.text();return e.log.debug({textBody:i}),i}o(Dg,"readBody");var zP={},Vd;function Ug(){if(!Vd)throw new jP.RuntimeError("Invalid State - no _lastLogger");return Vd}o(Ug,"getLastLogger");function WP(t){let e=zP[t];return e||(e=new VP.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Ug().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||Ug().error({status:i.status,body:await i.text()})})),e}o(WP,"getDispatcher");async function QP(t,e,r,n){Vd=e.log;let i=Lg(),s=Object.assign(BP,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Dg(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=WP(s.applicationId),d=t.headers.get("true-client-ip"),p=jd.get(e)??{},m={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Cg(t.headers)},f=s.logResponseBody?await Dg(c,e):void 0,y={time:Lg(),status:c.status,headers:Cg(c.headers),body:f},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:GP};l.enqueue(v),e.waitUntil(l.waitUntilFlushed())}),t}o(QP,"MoesifInboundPolicy");Rn.MoesifInboundPolicy=QP});var kg=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.OktaJwtInboundPolicy=void 0;var YP=Mt(),ZP=o(async(t,e,r,n)=>(0,YP.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");ba.OktaJwtInboundPolicy=ZP});var Fg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.PropelAuthJwtInboundPolicy=void 0;var XP=(fs(),Bi(hs)),eR=Mt(),Gd,tR=o(async(t,e,r,n)=>{if(!Gd)try{Gd=await(0,XP.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,eR.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Gd,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ea.PropelAuthJwtInboundPolicy=tR});var Hg=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var $e=Br(),et=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};G.ValidationError=et;var bi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};G.ArgumentUndefinedError=bi;var Ei=class extends et{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ei;function rR(t,e){if((0,$e.isUndefined)(t))throw new bi(e)}o(rR,"throwIfUndefined");G.throwIfUndefined=rR;function Bd(t,e){if((0,$e.isUndefinedOrNull)(t))throw new bi(e)}o(Bd,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Bd;function nR(t,e){if(Bd(t,e),!(0,$e.isString)(t))throw new Ei(e,"string")}o(nR,"throwIfNotString");G.throwIfNotString=nR;function iR(t,e){if(Bd(t,e),!(0,$e.isNumber)(t))throw new Ei(e,"number")}o(iR,"throwIfNotNumber");G.throwIfNotNumber=iR;var wi=class extends et{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};G.OptionUndefinedError=wi;var On=class extends et{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=On;function oR(t,e,r,n){if((0,$e.isUndefined)(n))throw new wi(t,e,r)}o(oR,"throwIfOptionUndefined");G.throwIfOptionUndefined=oR;function wa(t,e,r,n){if((0,$e.isUndefinedOrNull)(n))throw new wi(t,e,r)}o(wa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=wa;function sR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isString)(n))throw new On(t,e,r,"string")}o(sR,"throwIfOptionNotString");G.throwIfOptionNotString=sR;function aR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isNumber)(n))throw new On(t,e,r,"number")}o(aR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=aR;function cR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isObject)(n))throw new On(t,e,r,"object")}o(cR,"throwIfOptionNotObject");G.throwIfOptionNotObject=cR;function uR(t,e){if((0,$e.isUndefined)(t))throw new et(e)}o(uR,"throwIfStateUndefined");G.throwIfStateUndefined=uR;function va(t,e){if((0,$e.isUndefinedOrNull)(t))throw new et(e)}o(va,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=va;function lR(t,e){if(va(t,e),!(0,$e.isString)(t))throw new et(e);return!0}o(lR,"throwIfStateNotString");G.throwIfStateNotString=lR;function dR(t,e){if(va(t,e),!(0,$e.isNumber)(t))throw new et(e);return!0}o(dR,"throwIfStateNotNumber");G.throwIfStateNotNumber=dR;function pR(t,e){if(va(t,e),!(0,$e.isObject)(t))throw new et(e);return!0}o(pR,"throwIfStateNotObject");G.throwIfStateNotObject=pR});var qg=g(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.InMemoryRedisClient=xn.StandardRedisClient=void 0;var Kd=D(),Ta=Hg(),Jd=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ta.throwIfNotString)(e,"redisClientUrl"),(0,Ta.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ta.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Kd.SystemError("Redis client failed with 401: Unauthorized"):new Kd.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};xn.StandardRedisClient=Jd;var zd=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ta.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Kd.SystemError("The in-memory redis client only supports /rate-limit calls")}};xn.InMemoryRedisClient=zd});var Bg=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.RateLimitInboundPolicy=void 0;var hR=Er(),fR=ke(),mR=ur(),kt=D(),yR=ve(),$g=Ge(),vi=te(),jg=qg(),Vg=Br(),Sa=(0,hR.debug)("zuplo:policies:RateLimitInboundPolicy"),gR="strict",_R=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),bR=o(async t=>({key:`ip-${_R(t)}`}),"getIP"),ER=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),wR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ia;function vR(t,e){let r;if(Ia)return Ia;if(vi.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new jg.InMemoryRedisClient,Ia=r,r;let{authApiJWT:n,redisURL:i}=vi.Environment.instance;if(!(0,Vg.isString)(i))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,Vg.isString)(n))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=jg.StandardRedisClient.initialize(i,n,vi.Environment.instance.deploymentName??"unknown",vi.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Ia=r,r}o(vR,"getRedisClient");async function Gg(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(Gg,"getCountAndUpdateExpiry");function TR(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new kt.RuntimeError(u)}return c},"outerFunction")}o(TR,"wrapUserFunction");var SR="Retry-After",IR=o(async(t,e,r,n)=>{let i=Date.now(),s=$g.SystemLogMap.getLogger(e),a=o((u,l)=>{if(r.throwOnFailure)throw new kt.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[SR]=l.toString()),yR.HttpProblems.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:TR(r,n),user:ER,ip:bR,all:wR}[r.rateLimitBy],d=await l(t,e,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=vR(n,s),I=`bucket/${vi.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??gR)==="async"){let N=new fR.ZoneCache((0,mR.getPolicyCacheName)(n),{logger:$g.SystemLogMap.getLogger(e)}),oe=Gg(I,f,v,s,e.requestId),ee=await N.get(I);if(ee!==void 0&&ee<=Date.now()){Sa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${I}' (async mode)`);let fe=Math.round((ee-Date.now())/1e3);return c(y,fe)}return e.addEventListener("responseSending",fe=>{try{let Me=fe,E=Me.mutableResponse;Me.mutableResponse=(async()=>{let F=await oe;if(F.count>m){let Ye=Date.now()+F.ttlSeconds*1e3;return N.put(I,Ye,F.ttlSeconds).catch(Vi=>{throw s.error(Vi),Vi}),Sa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${I}' (async mode)`),c(y,F.ttlSeconds)}return E})()}catch(Me){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,Me)}}),t}let j=await Gg(I,f,v,s,e.requestId);return j.count>m?(Sa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${I}' (strict mode)`),c(y,j.ttlSeconds)):t}catch(u){return a(u.message,u),t}finally{let u=Date.now()-i;Sa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Aa.RateLimitInboundPolicy=IR});var Wg=g(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.ReadmeMetricsInboundPolicy=void 0;var AR=we(),Wd=te(),Kg=ta(),Qd;function Jg(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(Jg,"headersToNameValuePairs");function PR(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(PR,"queryToNameValueParis");function RR(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(RR,"parseIntOrUndefined");var zg={};async function OR(t,e,r,n){let i=new Date,s=Date.now();return Qd||(Qd={name:"zuplo",version:Wd.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Wd.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Wd.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Qd,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Jg(t.headers),queryString:PR(t.query)},response:{status:a.status,statusText:a.statusText,headers:Jg(a.headers),content:{size:RR(t.headers.get("content-length"))}}}]}}},d=zg[r.apiKey];if(!d){let p=r.apiKey;d=new AR.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),zg[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(OR,"ReadmeMetricsInboundPolicy");Pa.ReadmeMetricsInboundPolicy=OR});var Qg=g(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.RemoveHeadersInboundPolicy=void 0;var xR=ke(),NR=D(),CR=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new NR.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new xR.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Ra.RemoveHeadersInboundPolicy=CR});var Yg=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.RemoveHeadersOutboundPolicy=void 0;var LR=D(),DR=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new LR.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Oa.RemoveHeadersOutboundPolicy=DR});var Zg=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.RemoveQueryParamsInboundPolicy=void 0;var UR=ke(),MR=D(),kR=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new MR.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new UR.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");xa.RemoveQueryParamsInboundPolicy=kR});var Xg=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.ReplaceStringOutboundPolicy=void 0;var FR=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Na.ReplaceStringOutboundPolicy=FR});var t_=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.RequestSizeLimitInboundPolicy=void 0;var e_=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),HR=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?e_():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?e_():t},"RequestSizeLimitInboundPolicy");Ca.RequestSizeLimitInboundPolicy=HR});var La=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function qR(t,e,r){return`_${Cr(t+"_"+e+"_"+r)}`}o(qR,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=qR;function $R(t,e,r,n){return`_${Cr(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o($R,"getIdForParameterSchema");tt.getIdForParameterSchema=$R;function jR(t,e,r){return`_${Cr(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Cr(r.toLowerCase())}`}o(jR,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=jR;function VR(t,e){return`_${Cr(t)}__${Cr(e)}`}o(VR,"getIdForRefSchema");tt.getIdForRefSchema=VR;function Cr(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(Cr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Cr});var Ti=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getErrorsFromValidator=Ce.shouldReject=Ce.shouldLog=Ce.logErrors=Ce.validateParameters=Ce.getParametersForOperation=void 0;var GR=un(),Da=Lr(),BR=La(),KR=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Ce.getParametersForOperation=KR;var JR=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{if(u.required&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,BR.getIdForParameterSchema)(r,n,i,u.name),d=GR.Gateway.instance.schemaValidator[l],p=d(e[u.name]),m=(0,Ce.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Ce.validateParameters=JR;var zR=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");Ce.logErrors=zR;var WR=o(t=>t===Da.ValidationOptions.logOnly||t===Da.ValidationOptions.rejectAndLog,"shouldLog");Ce.shouldLog=WR;var QR=o(t=>t===Da.ValidationOptions.rejectOnly||t===Da.ValidationOptions.rejectAndLog,"shouldReject");Ce.shouldReject=QR;var YR=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");Ce.getErrorsFromValidator=YR});var r_=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.handleBodyValidation=void 0;var ZR=un(),XR=Lr(),Ua=ve(),eO=La(),Ke=Ti();async function tO(t,e,r){if(!r.validateBody||r.validateBody===XR.ValidationOptions.none)return;let n;try{n=await e.clone().json()}catch(f){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=Ua.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",y,[n],f),(0,Ke.shouldReject)(r.validateBody))return v}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Ua.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,eO.getIdForRequestBodySchema)(t.route.path,e.method,i),c=ZR.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Ua.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Ke.getErrorsFromValidator)(l),m=Ua.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",d,[n],p),(0,Ke.shouldReject)(r.validateBody))return m}o(tO,"handleBodyValidation");Ma.handleBodyValidation=tO});var n_=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.handleHeadersValidation=void 0;var rO=Lr(),nO=ve(),Si=Ti();function iO(t,e,r){if(!r.validateHeaders||r.validateHeaders===rO.ValidationOptions.none)return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,Si.getParametersForOperation)(t),s=(0,Si.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=nO.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Si.shouldLog)(r.validateHeaders)&&(0,Si.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Si.shouldReject)(r.validateHeaders))return c}}o(iO,"handleHeadersValidation");ka.handleHeadersValidation=iO});var i_=g(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.handlePathParameterValidation=void 0;var oO=Lr(),sO=ve(),Ii=Ti();function aO(t,e,r){if(!r.validatePathParameters||r.validatePathParameters===oO.ValidationOptions.none)return;let n=(0,Ii.getParametersForOperation)(t),i=(0,Ii.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=sO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ii.shouldLog)(r.validatePathParameters)&&(0,Ii.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ii.shouldReject)(r.validatePathParameters))return a}}o(aO,"handlePathParameterValidation");Fa.handlePathParameterValidation=aO});var o_=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.handleQueryParameterValidation=void 0;var cO=Lr(),uO=ve(),Ai=Ti();function lO(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters===cO.ValidationOptions.none)return;let n=(0,Ai.getParametersForOperation)(t),i=(0,Ai.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=uO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ai.shouldLog)(r.validateQueryParameters)&&(0,Ai.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ai.shouldReject)(r.validateQueryParameters))return a}}o(lO,"handleQueryParameterValidation");Ha.handleQueryParameterValidation=lO});var Lr=g(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy=Ft.ValidationOptions=void 0;var dO=r_(),pO=n_(),hO=i_(),fO=o_(),s_;(function(t){t.none="none",t.logOnly="log-only",t.rejectAndLog="reject-and-log",t.rejectOnly="reject-only"})(s_||(Ft.ValidationOptions=s_={}));var mO=o(async(t,e,r)=>{let n=(0,fO.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,hO.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,pO.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,dO.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");Ft.RequestValidationInboundPolicy=mO;Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy});var a_=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.RequireOriginInboundPolicy=void 0;var yO=ke(),gO=D(),_O=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new gO.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return yO.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");qa.RequireOriginInboundPolicy=_O});var c_=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.SetBodyInboundPolicy=void 0;var bO=ke(),EO=o(async(t,e,r)=>new bO.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");$a.SetBodyInboundPolicy=EO});var l_=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.SetHeadersInboundPolicy=void 0;var wO=ke(),u_=D(),vO=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new u_.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new u_.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new wO.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");ja.SetHeadersInboundPolicy=vO});var p_=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.SetHeadersOutboundPolicy=void 0;var d_=D(),TO=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new d_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new d_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Va.SetHeadersOutboundPolicy=TO});var f_=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.SetQueryParamsInboundPolicy=void 0;var SO=ke(),h_=D(),IO=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new h_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new h_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new SO.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Ga.SetQueryParamsInboundPolicy=IO});var m_=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetStatusOutboundPolicy=void 0;var AO=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Ba.SetStatusOutboundPolicy=AO});var y_=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SleepInboundPolicy=void 0;var PO=D(),RO=o(async t=>new Promise((r,n)=>{setTimeout(r,t)}),"sleep"),OO=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new PO.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await RO(r.sleepInMs),t},"SleepInboundPolicy");Ka.SleepInboundPolicy=OO});var __=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SupabaseJwtInboundPolicy=void 0;var xO=ke(),g_=D(),NO=ve(),CO=lr(),LO=Mt(),DO=o(async(t,e,r,n)=>{(0,CO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,LO.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof xO.ZuploRequest))throw new g_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new g_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?NO.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Ja.SupabaseJwtInboundPolicy=DO});var E_=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var UO=ur(),MO=_r(),b_=D(),kO=Ge(),FO=ys(),HO=lr(),qO=o(async(t,e,r,n)=>{(0,HO.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=new MO.MemoryZoneReadThroughCache((0,UO.getPolicyCacheName)(n),{logger:kO.SystemLogMap.getLogger(e)}),s=await i.get(n);if(!s){let a=await $O(r,e);i.put(n,a.access_token,a.expires_in-(r.expirationOffsetSeconds??300)),s=a.access_token}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");za.UpstreamAzureAdServiceAuthInboundPolicy=qO;async function $O(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,FO.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new b_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new b_.RuntimeError("Response returned from Azure AD is not in the expected format.")}o($O,"getAccessToken")});var v_=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var jO=ur(),VO=_r(),GO=D(),BO=Ge(),Yd=sn(),KO=lr(),w_="https://accounts.google.com/o/oauth2/token",Zd,JO=o(async(t,e,r,n)=>{(0,KO.optionValidator)(r,n).required("serviceAccountJson","string"),Zd||(Zd=await Yd.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=new VO.MemoryZoneReadThroughCache((0,jO.getPolicyCacheName)(n),{logger:BO.SystemLogMap.getLogger(e)}),a=await s.get(n);if(!a){let c=await(0,Yd.getTokenFromGcpServiceAccount)({serviceAccount:Zd,audience:w_,payload:i}),u=await(0,Yd.exchangeGgpJwtForIdToken)(w_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u.access_token)throw new GO.RuntimeError("Invalid OAuth response from Firebase");a=u.access_token,s.put(n,a,(u.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Wa.UpstreamFirebaseAdminAuthInboundPolicy=JO});var T_=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.sha256=void 0;async function zO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(zO,"sha256");Qa.sha256=zO});var S_=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.UpstreamFirebaseUserAuthInboundPolicy=void 0;var WO=ur(),QO=_r(),Nn=D(),YO=Ge(),ZO=T_(),Xd=sn(),XO=ta(),e0=lr(),t0="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",r0=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],ep,n0=o(async(t,e,r,n)=>{if((0,e0.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Nn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let d in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,d)){if(r0.indexOf(d)!==-1)throw new Nn.ConfigurationError(`Developer claim "${d}" is reserved and cannot be specified.`);i[d]=r.developerClaims[d]}}ep||(ep=await Xd.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new Nn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new Nn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,XO.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Nn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=new QO.MemoryZoneReadThroughCache((0,WO.getPolicyCacheName)(n),{logger:YO.SystemLogMap.getLogger(e)}),c={uid:s,claims:i},u=await(0,ZO.sha256)(JSON.stringify(c)),l=await a.get(u);if(!l){let d=await(0,Xd.getTokenFromGcpServiceAccount)({serviceAccount:ep,audience:t0,payload:c}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,m=await(0,Xd.exchangeFirebaseJwtForIdToken)(p,d,{retries:r.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new Nn.RuntimeError("Invalid token response from Firebase");l=m.idToken,a.put(u,l,(m.expiresIn?parseInt(m.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");Ya.UpstreamFirebaseUserAuthInboundPolicy=n0});var A_=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.UpstreamGcpJwtInboundPolicy=void 0;var I_=sn(),i0=lr(),tp,o0=o(async(t,e,r,n)=>{(0,i0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),tp||(tp=await I_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,I_.getTokenFromGcpServiceAccount)({serviceAccount:tp,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");Za.UpstreamGcpJwtInboundPolicy=o0});var O_=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.UpstreamGcpServiceAuthInboundPolicy=void 0;var P_=ur(),s0=Kc(),a0=_r(),c0=D(),rp=sn(),u0=lr(),R_="https://www.googleapis.com/oauth2/v4/token",np,l0=o(async(t,e,r,n)=>{(0,u0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),np||(np=await rp.GcpServiceAccount.init(r.serviceAccountJson));let i;r.useMemoryCacheOnly?i=new s0.MemoryCache((0,P_.getPolicyCacheName)(n)):i=new a0.MemoryZoneReadThroughCache((0,P_.getPolicyCacheName)(n),e);let s=await i.get(n);if(!s){let a=await(0,rp.getTokenFromGcpServiceAccount)({serviceAccount:np,audience:R_,payload:{target_audience:`${r.audience}`}}),{id_token:c}=await(0,rp.exchangeGgpJwtForIdToken)(R_,a,{retries:r.tokenRetries??3,retryDelayMs:10});if(!c)throw new c0.RuntimeError("Invalid token response from GCP");s=c,i.put(n,s,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamGcpServiceAuthInboundPolicy");Xa.UpstreamGcpServiceAuthInboundPolicy=l0});var N_=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ValidateJsonSchemaInbound=void 0;var d0=D(),x_=ve(),p0=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return x_.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new d0.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return x_.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");ec.ValidateJsonSchemaInbound=p0});var C_=g(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.serialize=dr.ContentTypes=void 0;dr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function h0(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(dr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(dr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(h0,"serialize");dr.serialize=h0});var L_=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.ServiceProviderImpl=void 0;var f0=D(),ip=class t{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,r){if(this.services.get(e))throw new f0.SystemError(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};tc.ServiceProviderImpl=ip});var D_=g(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var m0={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};op.default=m0});var ke=g(h=>{"use strict";var y0=h&&h.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),U_=h&&h.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&y0(e,t,r)},g0=h&&h.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(h,"__esModule",{value:!0});h.ReadmeMetricsInboundPolicy=h.RateLimitInboundPolicy=h.BasicRateLimitInboundPolicy=h.PropelAuthJwtInboundPolicy=h.OpenIdJwtInboundPolicy=h.OktaJwtInboundPolicy=h.setMoesifContext=h.MoesifInboundPolicy=h.MockApiInboundPolicy=h.JWTScopeValidationInboundPolicy=h.GeoFilterInboundPolicy=h.FormDataToJsonInboundPolicy=h.FirebaseJwtInboundPolicy=h.CompositeInboundPolicy=h.CognitoJwtInboundPolicy=h.ClerkJwtInboundPolicy=h.ClearHeadersOutboundPolicy=h.ClearHeadersInboundPolicy=h.ChangeMethodInboundPolicy=h.CachingInboundPolicy=h.BasicAuthInboundPolicy=h.Auth0JwtInboundPolicy=h.ApiKeyInboundPolicy=h.ApiAuthKeyInboundPolicy=h.AmberfloMeteringPolicy=h.AmberfloMeteringInboundPolicy=h.AuditLogPlugin=h.AuditLogDataStaxProvider=h.HttpStatusCode=h.webSocketPipelineHandler=h.webSocketHandler=h.urlRewriteHandler=h.urlForwardHandler=h.redirectHandler=h.openApiSpecHandler=h.awsLambdaHandler=h.AwsLambdaHandlerExtensions=h.purgeGatewayCache=h.Handler=h.originalFetch=h.ConfigurationError=h.isZuploReadableEnvVariableName=h.isRestrictedEnvVariableName=h.environment=h.ContextData=h.ResponseSentEvent=h.ResponseSendingEvent=h.VALID_COMPATIBILITY_DATES=h.ZoneCache=h.MemoryZoneReadThroughCache=void 0;h.sanitizedIdentifierName=h.getRawOperationDataIdentifierName=h.getIdForRequestBodySchema=h.getIdForRefSchema=h.getIdForParameterSchema=h.SystemLogMap=h.httpStatuses=h.SYSTEM_LOGGER=h.API_KEY=h.ServiceProviderImpl=h.serialize=h.ContentTypes=h.Router=h.LookupResult=h.SystemRouteName=h.ZuploRequest=h.ProblemResponseFormatter=h.HttpProblems=h.ValidateJsonSchemaInbound=h.UpstreamGcpServiceAuthInboundPolicy=h.UpstreamGcpJwtInboundPolicy=h.UpstreamFirebaseUserAuthInboundPolicy=h.UpstreamFirebaseAdminAuthInboundPolicy=h.UpstreamAzureAdServiceAuthInboundPolicy=h.SupabaseJwtInboundPolicy=h.SleepInboundPolicy=h.SetStatusOutboundPolicy=h.SetQueryParamsInboundPolicy=h.SetHeadersOutboundPolicy=h.SetHeadersInboundPolicy=h.SetBodyInboundPolicy=h.RequireOriginInboundPolicy=h.SchemaBasedRequestValidation=h.RequestValidationInboundPolicy=h.RequestSizeLimitInboundPolicy=h.ReplaceStringOutboundPolicy=h.RemoveQueryParamsInboundPolicy=h.RemoveHeadersOutboundPolicy=h.RemoveHeadersInboundPolicy=void 0;qp();var _0=_r();Object.defineProperty(h,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return _0.MemoryZoneReadThroughCache}});var b0=Wc();Object.defineProperty(h,"ZoneCache",{enumerable:!0,get:function(){return b0.ZoneCache}});var E0=jp();Object.defineProperty(h,"VALID_COMPATIBILITY_DATES",{enumerable:!0,get:function(){return E0.VALID_COMPATIBILITY_DATES}});var M_=wr();Object.defineProperty(h,"ResponseSendingEvent",{enumerable:!0,get:function(){return M_.ResponseSendingEvent}});Object.defineProperty(h,"ResponseSentEvent",{enumerable:!0,get:function(){return M_.ResponseSentEvent}});var w0=oy();Object.defineProperty(h,"ContextData",{enumerable:!0,get:function(){return w0.ContextData}});var sp=Xl();Object.defineProperty(h,"environment",{enumerable:!0,get:function(){return sp.environment}});Object.defineProperty(h,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return sp.isRestrictedEnvVariableName}});Object.defineProperty(h,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return sp.isZuploReadableEnvVariableName}});var v0=D();Object.defineProperty(h,"ConfigurationError",{enumerable:!0,get:function(){return v0.ConfigurationError}});var T0=td();Object.defineProperty(h,"originalFetch",{enumerable:!0,get:function(){return T0.originalFetch}});var k_=fy();Object.defineProperty(h,"Handler",{enumerable:!0,get:function(){return k_.Handler}});Object.defineProperty(h,"purgeGatewayCache",{enumerable:!0,get:function(){return k_.purgeGatewayCache}});var F_=Ny();Object.defineProperty(h,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return F_.AwsLambdaHandlerExtensions}});Object.defineProperty(h,"awsLambdaHandler",{enumerable:!0,get:function(){return F_.awsLambdaHandler}});var S0=Ly();Object.defineProperty(h,"openApiSpecHandler",{enumerable:!0,get:function(){return S0.openApiSpecHandler}});var I0=Dy();Object.defineProperty(h,"redirectHandler",{enumerable:!0,get:function(){return I0.redirectHandler}});var A0=My();Object.defineProperty(h,"urlForwardHandler",{enumerable:!0,get:function(){return A0.urlForwardHandler}});var P0=Fy();Object.defineProperty(h,"urlRewriteHandler",{enumerable:!0,get:function(){return P0.urlRewriteHandler}});var R0=qy();Object.defineProperty(h,"webSocketHandler",{enumerable:!0,get:function(){return R0.webSocketHandler}});var O0=Vy();Object.defineProperty(h,"webSocketPipelineHandler",{enumerable:!0,get:function(){return O0.webSocketPipelineHandler}});var x0=fu();Object.defineProperty(h,"HttpStatusCode",{enumerable:!0,get:function(){return x0.HttpStatusCode}});U_(Yy(),h);U_(eg(),h);var N0=tg();Object.defineProperty(h,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return N0.AuditLogDataStaxProvider}});var C0=ng();Object.defineProperty(h,"AuditLogPlugin",{enumerable:!0,get:function(){return C0.AuditLogPlugin}});var H_=lg();Object.defineProperty(h,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringInboundPolicy}});Object.defineProperty(h,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringPolicy}});var q_=fg();Object.defineProperty(h,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiAuthKeyInboundPolicy}});Object.defineProperty(h,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiKeyInboundPolicy}});var L0=mg();Object.defineProperty(h,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return L0.Auth0JwtInboundPolicy}});var D0=yg();Object.defineProperty(h,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return D0.BasicAuthInboundPolicy}});var U0=gg();Object.defineProperty(h,"CachingInboundPolicy",{enumerable:!0,get:function(){return U0.CachingInboundPolicy}});var M0=_g();Object.defineProperty(h,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return M0.ChangeMethodInboundPolicy}});var k0=bg();Object.defineProperty(h,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return k0.ClearHeadersInboundPolicy}});var F0=Eg();Object.defineProperty(h,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return F0.ClearHeadersOutboundPolicy}});var H0=wg();Object.defineProperty(h,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return H0.ClerkJwtInboundPolicy}});var q0=Tg();Object.defineProperty(h,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return q0.CognitoJwtInboundPolicy}});var $0=Ig();Object.defineProperty(h,"CompositeInboundPolicy",{enumerable:!0,get:function(){return $0.CompositeInboundPolicy}});var j0=Ag();Object.defineProperty(h,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return j0.FirebaseJwtInboundPolicy}});var V0=Pg();Object.defineProperty(h,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return V0.FormDataToJsonInboundPolicy}});var G0=Rg();Object.defineProperty(h,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return G0.GeoFilterInboundPolicy}});var B0=Og();Object.defineProperty(h,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return B0.JWTScopeValidationInboundPolicy}});var K0=Ng();Object.defineProperty(h,"MockApiInboundPolicy",{enumerable:!0,get:function(){return K0.MockApiInboundPolicy}});var $_=Mg();Object.defineProperty(h,"MoesifInboundPolicy",{enumerable:!0,get:function(){return $_.MoesifInboundPolicy}});Object.defineProperty(h,"setMoesifContext",{enumerable:!0,get:function(){return $_.setMoesifContext}});var J0=kg();Object.defineProperty(h,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return J0.OktaJwtInboundPolicy}});var z0=Mt();Object.defineProperty(h,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return z0.OpenIdJwtInboundPolicy}});var W0=Fg();Object.defineProperty(h,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return W0.PropelAuthJwtInboundPolicy}});var j_=Bg();Object.defineProperty(h,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});Object.defineProperty(h,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});var Q0=Wg();Object.defineProperty(h,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return Q0.ReadmeMetricsInboundPolicy}});var Y0=Qg();Object.defineProperty(h,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return Y0.RemoveHeadersInboundPolicy}});var Z0=Yg();Object.defineProperty(h,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return Z0.RemoveHeadersOutboundPolicy}});var X0=Zg();Object.defineProperty(h,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return X0.RemoveQueryParamsInboundPolicy}});var ex=Xg();Object.defineProperty(h,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return ex.ReplaceStringOutboundPolicy}});var tx=t_();Object.defineProperty(h,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return tx.RequestSizeLimitInboundPolicy}});var V_=Lr();Object.defineProperty(h,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return V_.RequestValidationInboundPolicy}});Object.defineProperty(h,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return V_.SchemaBasedRequestValidation}});var rx=a_();Object.defineProperty(h,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return rx.RequireOriginInboundPolicy}});var nx=c_();Object.defineProperty(h,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return nx.SetBodyInboundPolicy}});var ix=l_();Object.defineProperty(h,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return ix.SetHeadersInboundPolicy}});var ox=p_();Object.defineProperty(h,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return ox.SetHeadersOutboundPolicy}});var sx=f_();Object.defineProperty(h,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return sx.SetQueryParamsInboundPolicy}});var ax=m_();Object.defineProperty(h,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return ax.SetStatusOutboundPolicy}});var cx=y_();Object.defineProperty(h,"SleepInboundPolicy",{enumerable:!0,get:function(){return cx.SleepInboundPolicy}});var ux=__();Object.defineProperty(h,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return ux.SupabaseJwtInboundPolicy}});var lx=E_();Object.defineProperty(h,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return lx.UpstreamAzureAdServiceAuthInboundPolicy}});var dx=v_();Object.defineProperty(h,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return dx.UpstreamFirebaseAdminAuthInboundPolicy}});var px=S_();Object.defineProperty(h,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return px.UpstreamFirebaseUserAuthInboundPolicy}});var hx=A_();Object.defineProperty(h,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return hx.UpstreamGcpJwtInboundPolicy}});var fx=O_();Object.defineProperty(h,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return fx.UpstreamGcpServiceAuthInboundPolicy}});var mx=N_();Object.defineProperty(h,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return mx.ValidateJsonSchemaInbound}});var yx=ve();Object.defineProperty(h,"HttpProblems",{enumerable:!0,get:function(){return yx.HttpProblems}});var gx=oo();Object.defineProperty(h,"ProblemResponseFormatter",{enumerable:!0,get:function(){return gx.ProblemResponseFormatter}});var _x=Wn();Object.defineProperty(h,"ZuploRequest",{enumerable:!0,get:function(){return _x.ZuploRequest}});var bx=Sr();Object.defineProperty(h,"SystemRouteName",{enumerable:!0,get:function(){return bx.SystemRouteName}});var G_=Gl();Object.defineProperty(h,"LookupResult",{enumerable:!0,get:function(){return G_.LookupResult}});Object.defineProperty(h,"Router",{enumerable:!0,get:function(){return G_.Router}});var B_=C_();Object.defineProperty(h,"ContentTypes",{enumerable:!0,get:function(){return B_.ContentTypes}});Object.defineProperty(h,"serialize",{enumerable:!0,get:function(){return B_.serialize}});var Ex=L_();Object.defineProperty(h,"ServiceProviderImpl",{enumerable:!0,get:function(){return Ex.ServiceProviderImpl}});var K_=Tu();Object.defineProperty(h,"API_KEY",{enumerable:!0,get:function(){return K_.API_KEY}});Object.defineProperty(h,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return K_.SYSTEM_LOGGER}});var wx=D_();Object.defineProperty(h,"httpStatuses",{enumerable:!0,get:function(){return g0(wx).default}});var vx=Ge();Object.defineProperty(h,"SystemLogMap",{enumerable:!0,get:function(){return vx.SystemLogMap}});var Pi=La();Object.defineProperty(h,"getIdForParameterSchema",{enumerable:!0,get:function(){return Pi.getIdForParameterSchema}});Object.defineProperty(h,"getIdForRefSchema",{enumerable:!0,get:function(){return Pi.getIdForRefSchema}});Object.defineProperty(h,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Pi.getIdForRequestBodySchema}});Object.defineProperty(h,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Pi.getRawOperationDataIdentifierName}});Object.defineProperty(h,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Pi.sanitizedIdentifierName}})});var J_=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.BaseCryptoBeta=Cn.supportedDigests=void 0;Cn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var ap=class{static{o(this,"BaseCryptoBeta")}};Cn.BaseCryptoBeta=ap});var z_=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.WorkerCryptoBeta=void 0;var cp=J_(),Tx=D(),up=class extends cp.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!cp.supportedDigests.includes(e.toLowerCase()))throw new Tx.RuntimeError(`Algorithm ${e} is not supported. Try using ${cp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};rc.WorkerCryptoBeta=up});var W_=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.BaseKeyValueStore=void 0;var lp=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};nc.BaseKeyValueStore=lp});var Y_=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.WorkerKeyValueStore=void 0;var Q_=D(),Sx=W_(),dp=class extends Sx.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=globalThis.ZUPLO_KV;if(!n)throw new Q_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,r,n){if(typeof e!="string")throw new Q_.ConfigurationError("value must be of type string");return this.#e.put(e,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(e,r){return this.#e.get(e,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};ic.WorkerKeyValueStore=dp});var Ot=g(ct=>{"use strict";var Ix=ct&&ct.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ax=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ix(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Ax(ke(),ct);var Px=z_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Px.WorkerCryptoBeta}});var Rx=Y_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return Rx.WorkerKeyValueStore}})});var UN={};Gi(UN,{GraphQLComplexityLimitInboundPolicy:()=>Ob,GraphQLDisableIntrospectionInboundPolicy:()=>Nb});module.exports=Bi(UN);var Gn=Mp(Ot());function B(t,e){if(!!!t)throw new Error(e)}o(B,"devAssert");function be(t){return typeof t=="object"&&t!==null}o(be,"isObjectLike");function Tt(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(Tt,"invariant");var Ox=/\r\n|[\n\r]/g;function Ln(t,e){let r=0,n=1;for(let i of t.body.matchAll(Ox)){if(typeof i.index=="number"||Tt(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(Ln,"getLocation");function pp(t){return oc(t.source,Ln(t.source,t.start))}o(pp,"printLocation");function oc(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?r:0,u=e.column+c,l=`${t.name}:${a}:${u}
|
|
65
|
+
`),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new Zs(await n.text())}};cr.DynaTraceMetricsTransport=Ys;var Zs=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};cr.DynaTraceMetricsError=Zs});var eg=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.DynatraceMetricsPlugin=wn.DataDogMetricsPlugin=void 0;var jA=Zy();Object.defineProperty(wn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return jA.DataDogMetricsPlugin}});var VA=Xy();Object.defineProperty(wn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return VA.DynatraceMetricsPlugin}})});var tg=g(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.AuditLogDataStaxProvider=void 0;var Nd=class{static{o(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};Xs.AuditLogDataStaxProvider=Nd});var ng=g(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.AuditLogPlugin=void 0;var GA=Rt(),BA=we(),Cd=class extends GA.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Ld(e,this.#e,this.#t)}};ea.AuditLogPlugin=Cd;var rg=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),KA={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ld=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...KA};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,e.addRequestHook(this.#o),this.#r=new BA.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async e=>{await this.#t.writeLogBatch(e)};#i=async(e,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?rg(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?rg(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let i=new Date,s=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var ta=g(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.getValueFromRequestUser=vn.statusCodesStringToNumberArray=void 0;var ig=D(),og=new Map;function JA(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=og.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return og.set(t,n),n}o(JA,"statusCodesStringToNumberArray");vn.statusCodesStringToNumberArray=JA;function zA(t,e,r){if(!e.startsWith("."))throw new ig.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new ig.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(zA,"getValueFromRequestUser");vn.getValueFromRequestUser=zA});var lg=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.AmberfloMeteringInboundPolicy=Tn.AmberfloMeteringPolicy=void 0;var sg=D(),WA=we(),ag=ta(),ug=new WeakMap,cg={},Dd=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){ug.set(e,r)}};Tn.AmberfloMeteringPolicy=Dd;async function QA(t,e,r,n){if(!r.statusCodes)throw new sg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,ag.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=ug.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new sg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,ag.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},m=cg[r.apiKey];if(!m){let f=r.apiKey,y=t.headers.get("zm-test-id")??"";m=new WA.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",I=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});I.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${I.status}: ${await I.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),cg[f]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}o(QA,"AmberfloMeteringInboundPolicy");Tn.AmberfloMeteringInboundPolicy=QA});var ur=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.getPolicyCacheName=void 0;function YA(t){return`zuplo-policy-${t}`}o(YA,"getPolicyCacheName");ra.getPolicyCacheName=YA});var fg=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.ApiAuthKeyInboundPolicy=Sn.ApiKeyInboundPolicy=void 0;var ZA=ur(),XA=_r(),dg=Xl(),Ud=D(),eP=Ot(),Md=Ge(),kd=te(),tP=ys(),pg="key-metadata-cache-type";function rP(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(rP,"getKeyValue");async function hg(t,e,r,n){if(!r.bucketName)if(dg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=dg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Ud.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Ud.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:eP.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=rP(a,i);if(!c||c==="")return s("No key present");let u=await nP(c),l=new XA.MemoryZoneReadThroughCache((0,ZA.getPolicyCacheName)(n),{logger:Md.SystemLogMap.getLogger(e)}),d=await l.get(u);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==pg&&Md.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${d.typeId}'`,d),s("Authorization Failed");let p={key:c},m=await(0,tP.fetchRetry)({retryDelayMs:5,retries:2,logger:Md.SystemLogMap.getLogger(e)},`${kd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":kd.Environment.instance.deploymentName??"unknown","User-Agent":kd.Environment.instance.systemUserAgent},body:JSON.stringify(p)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),T=JSON.parse(v);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new Ud.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${m.status}`)}let f=await m.json(),y={isValid:!0,typeId:pg,user:{sub:f.name,data:f.metadata}};return t.user=y.user,l.put(u,y,i.cacheTtlSeconds),t}o(hg,"ApiKeyInboundPolicy");Sn.ApiKeyInboundPolicy=hg;async function nP(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(nP,"hashValue");Sn.ApiAuthKeyInboundPolicy=hg});var Mt=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.OpenIdJwtInboundPolicy=void 0;var Hd=(fs(),Bi(hs)),qd=D(),iP=ve(),Fd={},oP=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new qd.ConfigurationError("Invalid State - jwkUrl not set");Fd[e.jwkUrl]||(Fd[e.jwkUrl]=(0,Hd.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Hd.jwtVerify)(t,Fd[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),sP=o(async(t,e)=>{let r;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Hd.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),aP=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(m=>iP.HttpProblems.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new qd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?oP:sP,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=i.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(f){let y=new URL(t.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,f):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,f),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");na.OpenIdJwtInboundPolicy=aP});var mg=g(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.Auth0JwtInboundPolicy=void 0;var cP=Mt(),uP=o(async(t,e,r,n)=>(0,cP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");ia.Auth0JwtInboundPolicy=uP});var yg=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.BasicAuthInboundPolicy=void 0;var lP=ve(),dP=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>lP.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===f);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");oa.BasicAuthInboundPolicy=dP});var gg=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.CachingInboundPolicy=void 0;var pP=ur(),hP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function fP(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(fP,"digestMessage");var mP=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await fP(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function yP(t,e,r,n){let i=await caches.open(`${(0,pP.getPolicyCacheName)(n)}-${r.cacheId??""}`),s=r?.cacheHttpMethods?.map(u=>u.toUpperCase())??["GET"],a=await mP(t,r),c=await i.match(a);return c||(e.addEventListener("responseSent",u=>{try{let l=r.statusCodes??[200,206,301,302,303,404,410],d=u.response.clone();if(!l.includes(d.status)||!s.includes(t.method.toUpperCase()))return;let p=r?.expirationSecondsTtl??60,m=new Response(d.body,d);hP.forEach(f=>m.headers.delete(f)),m.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(i.put(a,m))}catch(l){e.log.error(`Error in caching-inbound-policy '${n}': "${l.message}"`,l)}}),t)}o(yP,"CachingInboundPolicy");sa.CachingInboundPolicy=yP});var _g=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.ChangeMethodInboundPolicy=void 0;var gP=D(),_P=Wn(),bP=o(async(t,e,r,n)=>{if(!r.method)throw new gP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new _P.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");aa.ChangeMethodInboundPolicy=bP});var bg=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.ClearHeadersInboundPolicy=void 0;var EP=ke(),wP=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new EP.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");ca.ClearHeadersInboundPolicy=wP});var Eg=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.ClearHeadersOutboundPolicy=void 0;var vP=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");ua.ClearHeadersOutboundPolicy=vP});var wg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.ClerkJwtInboundPolicy=void 0;var TP=Mt(),SP=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,TP.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");la.ClerkJwtInboundPolicy=SP});var Tg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.CognitoJwtInboundPolicy=void 0;var vg=D(),IP=Mt(),AP=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new vg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new vg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,IP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");da.CognitoJwtInboundPolicy=AP});var Ig=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.CompositeInboundPolicy=void 0;var PP=D(),RP=un(),Sg=Qn(),OP=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new PP.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=RP.Gateway.instance,s=(0,Sg.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Sg.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");pa.CompositeInboundPolicy=OP});var lr=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.optionValidator=void 0;var _i=D();function xP(t,e){let r=o((s,a,c)=>{let u=t[s];if(!(c&&u===void 0)){if(u===void 0)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new _i.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(xP,"optionValidator");ha.optionValidator=xP});var Ag=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.FirebaseJwtInboundPolicy=void 0;var NP=lr(),CP=Mt(),LP=o(async(t,e,r,n)=>((0,NP.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,CP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");fa.FirebaseJwtInboundPolicy=LP});var Pg=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.FormDataToJsonInboundPolicy=void 0;var DP=ke(),UP=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new DP.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");ma.FormDataToJsonInboundPolicy=UP});var Rg=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.GeoFilterInboundPolicy=void 0;var MP=D(),kP=ve(),In="__unknown__",FP=o(async(t,e,r,n)=>{let i={allow:{countries:Pn(r.allow?.countries,"allow.countries",n),regionCodes:Pn(r.allow?.regionCodes,"allow.regionCode",n),asns:Pn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Pn(r.block?.countries,"block.countries",n),regionCodes:Pn(r.block?.regionCodes,"block.regionCode",n),asns:Pn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??In,a=e.incomingRequestProperties.regionCode?.toLowerCase()??In,c=e.incomingRequestProperties.asn?.toString()??In,u=i.ignoreUnknown&&s===In,l=i.ignoreUnknown&&a===In,d=i.ignoreUnknown&&c===In,p=i.allow.countries,m=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||m.length>0&&!m.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return An(t,e,n,s,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?An(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");ya.GeoFilterInboundPolicy=FP;function An(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),kP.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(An,"blockedResponse");function Pn(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new MP.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(Pn,"toLowerStringArray")});var Og=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.JWTScopeValidationInboundPolicy=void 0;var HP=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");ga.JWTScopeValidationInboundPolicy=HP});var Ng=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.MockApiInboundPolicy=void 0;var qP=ve(),$P=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return $d(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return $d(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return xg(a[c])}else return a.length>0?xg(a[0]):$d(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");_a.MockApiInboundPolicy=$P;function xg(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(xg,"generateResponse");var $d=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return qP.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Mg=g(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.MoesifInboundPolicy=Rn.setMoesifContext=void 0;var jP=D(),VP=we(),GP="Incoming",BP={logRequestBody:!0,logResponseBody:!0};function Cg(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(Cg,"headersToObject");function Lg(){return new Date().toISOString()}o(Lg,"timestamp");var jd=new WeakMap,KP={};function JP(t,e){let r=jd.get(t);r||(r=KP);let n=Object.assign({...r},e);jd.set(t,n)}o(JP,"setMoesifContext");Rn.setMoesifContext=JP;async function Dg(t,e){let r=t.headers.get("content-type"),n=t.clone();if(r&&r.indexOf("json")!==0)try{return await n.json()}catch(s){e.log.error(s)}let i=await n.text();return e.log.debug({textBody:i}),i}o(Dg,"readBody");var zP={},Vd;function Ug(){if(!Vd)throw new jP.RuntimeError("Invalid State - no _lastLogger");return Vd}o(Ug,"getLastLogger");function WP(t){let e=zP[t];return e||(e=new VP.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Ug().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||Ug().error({status:i.status,body:await i.text()})})),e}o(WP,"getDispatcher");async function QP(t,e,r,n){Vd=e.log;let i=Lg(),s=Object.assign(BP,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Dg(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=WP(s.applicationId),d=t.headers.get("true-client-ip"),p=jd.get(e)??{},m={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Cg(t.headers)},f=s.logResponseBody?await Dg(c,e):void 0,y={time:Lg(),status:c.status,headers:Cg(c.headers),body:f},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:GP};l.enqueue(v),e.waitUntil(l.waitUntilFlushed())}),t}o(QP,"MoesifInboundPolicy");Rn.MoesifInboundPolicy=QP});var kg=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.OktaJwtInboundPolicy=void 0;var YP=Mt(),ZP=o(async(t,e,r,n)=>(0,YP.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");ba.OktaJwtInboundPolicy=ZP});var Fg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.PropelAuthJwtInboundPolicy=void 0;var XP=(fs(),Bi(hs)),eR=Mt(),Gd,tR=o(async(t,e,r,n)=>{if(!Gd)try{Gd=await(0,XP.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,eR.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Gd,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ea.PropelAuthJwtInboundPolicy=tR});var Hg=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var $e=Br(),et=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};G.ValidationError=et;var bi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};G.ArgumentUndefinedError=bi;var Ei=class extends et{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ei;function rR(t,e){if((0,$e.isUndefined)(t))throw new bi(e)}o(rR,"throwIfUndefined");G.throwIfUndefined=rR;function Bd(t,e){if((0,$e.isUndefinedOrNull)(t))throw new bi(e)}o(Bd,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Bd;function nR(t,e){if(Bd(t,e),!(0,$e.isString)(t))throw new Ei(e,"string")}o(nR,"throwIfNotString");G.throwIfNotString=nR;function iR(t,e){if(Bd(t,e),!(0,$e.isNumber)(t))throw new Ei(e,"number")}o(iR,"throwIfNotNumber");G.throwIfNotNumber=iR;var wi=class extends et{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};G.OptionUndefinedError=wi;var On=class extends et{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=On;function oR(t,e,r,n){if((0,$e.isUndefined)(n))throw new wi(t,e,r)}o(oR,"throwIfOptionUndefined");G.throwIfOptionUndefined=oR;function wa(t,e,r,n){if((0,$e.isUndefinedOrNull)(n))throw new wi(t,e,r)}o(wa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=wa;function sR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isString)(n))throw new On(t,e,r,"string")}o(sR,"throwIfOptionNotString");G.throwIfOptionNotString=sR;function aR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isNumber)(n))throw new On(t,e,r,"number")}o(aR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=aR;function cR(t,e,r,n){if(wa(t,e,r,n),!(0,$e.isObject)(n))throw new On(t,e,r,"object")}o(cR,"throwIfOptionNotObject");G.throwIfOptionNotObject=cR;function uR(t,e){if((0,$e.isUndefined)(t))throw new et(e)}o(uR,"throwIfStateUndefined");G.throwIfStateUndefined=uR;function va(t,e){if((0,$e.isUndefinedOrNull)(t))throw new et(e)}o(va,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=va;function lR(t,e){if(va(t,e),!(0,$e.isString)(t))throw new et(e);return!0}o(lR,"throwIfStateNotString");G.throwIfStateNotString=lR;function dR(t,e){if(va(t,e),!(0,$e.isNumber)(t))throw new et(e);return!0}o(dR,"throwIfStateNotNumber");G.throwIfStateNotNumber=dR;function pR(t,e){if(va(t,e),!(0,$e.isObject)(t))throw new et(e);return!0}o(pR,"throwIfStateNotObject");G.throwIfStateNotObject=pR});var qg=g(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.InMemoryRedisClient=xn.StandardRedisClient=void 0;var Kd=D(),Ta=Hg(),Jd=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ta.throwIfNotString)(e,"redisClientUrl"),(0,Ta.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ta.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Kd.SystemError("Redis client failed with 401: Unauthorized"):new Kd.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};xn.StandardRedisClient=Jd;var zd=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ta.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Kd.SystemError("The in-memory redis client only supports /rate-limit calls")}};xn.InMemoryRedisClient=zd});var Bg=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.RateLimitInboundPolicy=void 0;var hR=Er(),fR=ke(),mR=ur(),kt=D(),yR=ve(),$g=Ge(),vi=te(),jg=qg(),Vg=Br(),Sa=(0,hR.debug)("zuplo:policies:RateLimitInboundPolicy"),gR="strict",_R=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),bR=o(async t=>({key:`ip-${_R(t)}`}),"getIP"),ER=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),wR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ia;function vR(t,e){let r;if(Ia)return Ia;if(vi.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new jg.InMemoryRedisClient,Ia=r,r;let{authApiJWT:n,redisURL:i}=vi.Environment.instance;if(!(0,Vg.isString)(i))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,Vg.isString)(n))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=jg.StandardRedisClient.initialize(i,n,vi.Environment.instance.deploymentName??"unknown",vi.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Ia=r,r}o(vR,"getRedisClient");async function Gg(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(Gg,"getCountAndUpdateExpiry");function TR(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new kt.RuntimeError(u)}return c},"outerFunction")}o(TR,"wrapUserFunction");var SR="Retry-After",IR=o(async(t,e,r,n)=>{let i=Date.now(),s=$g.SystemLogMap.getLogger(e),a=o((u,l)=>{if(r.throwOnFailure)throw new kt.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[SR]=l.toString()),yR.HttpProblems.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:TR(r,n),user:ER,ip:bR,all:wR}[r.rateLimitBy],d=await l(t,e,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=vR(n,s),I=`bucket/${vi.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??gR)==="async"){let N=new fR.ZoneCache((0,mR.getPolicyCacheName)(n),{logger:$g.SystemLogMap.getLogger(e)}),oe=Gg(I,f,v,s,e.requestId),ee=await N.get(I);if(ee!==void 0&&ee<=Date.now()){Sa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${I}' (async mode)`);let fe=Math.round((ee-Date.now())/1e3);return c(y,fe)}return e.addEventListener("responseSending",fe=>{try{let Me=fe,E=Me.mutableResponse;Me.mutableResponse=(async()=>{let F=await oe;if(F.count>m){let Ye=Date.now()+F.ttlSeconds*1e3;return N.put(I,Ye,F.ttlSeconds).catch(Vi=>{throw s.error(Vi),Vi}),Sa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${I}' (async mode)`),c(y,F.ttlSeconds)}return E})()}catch(Me){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,Me)}}),t}let j=await Gg(I,f,v,s,e.requestId);return j.count>m?(Sa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${I}' (strict mode)`),c(y,j.ttlSeconds)):t}catch(u){return a(u.message,u),t}finally{let u=Date.now()-i;Sa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Aa.RateLimitInboundPolicy=IR});var Wg=g(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.ReadmeMetricsInboundPolicy=void 0;var AR=we(),Wd=te(),Kg=ta(),Qd;function Jg(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(Jg,"headersToNameValuePairs");function PR(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(PR,"queryToNameValueParis");function RR(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(RR,"parseIntOrUndefined");var zg={};async function OR(t,e,r,n){let i=new Date,s=Date.now();return Qd||(Qd={name:"zuplo",version:Wd.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Wd.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Wd.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Qd,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Jg(t.headers),queryString:PR(t.query)},response:{status:a.status,statusText:a.statusText,headers:Jg(a.headers),content:{size:RR(t.headers.get("content-length"))}}}]}}},d=zg[r.apiKey];if(!d){let p=r.apiKey;d=new AR.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),zg[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(OR,"ReadmeMetricsInboundPolicy");Pa.ReadmeMetricsInboundPolicy=OR});var Qg=g(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.RemoveHeadersInboundPolicy=void 0;var xR=ke(),NR=D(),CR=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new NR.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new xR.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Ra.RemoveHeadersInboundPolicy=CR});var Yg=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.RemoveHeadersOutboundPolicy=void 0;var LR=D(),DR=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new LR.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Oa.RemoveHeadersOutboundPolicy=DR});var Zg=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.RemoveQueryParamsInboundPolicy=void 0;var UR=ke(),MR=D(),kR=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new MR.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new UR.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");xa.RemoveQueryParamsInboundPolicy=kR});var Xg=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.ReplaceStringOutboundPolicy=void 0;var FR=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Na.ReplaceStringOutboundPolicy=FR});var t_=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.RequestSizeLimitInboundPolicy=void 0;var e_=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),HR=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?e_():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?e_():t},"RequestSizeLimitInboundPolicy");Ca.RequestSizeLimitInboundPolicy=HR});var La=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function qR(t,e,r){return`_${Cr(t+"_"+e+"_"+r)}`}o(qR,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=qR;function $R(t,e,r,n){return`_${Cr(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o($R,"getIdForParameterSchema");tt.getIdForParameterSchema=$R;function jR(t,e,r){return`_${Cr(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Cr(r.toLowerCase())}`}o(jR,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=jR;function VR(t,e){return`_${Cr(t)}__${Cr(e)}`}o(VR,"getIdForRefSchema");tt.getIdForRefSchema=VR;function Cr(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(Cr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Cr});var Ti=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getErrorsFromValidator=Ce.shouldReject=Ce.shouldLog=Ce.logErrors=Ce.validateParameters=Ce.getParametersForOperation=void 0;var GR=un(),Da=Lr(),BR=La(),KR=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Ce.getParametersForOperation=KR;var JR=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{if(u.required&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,BR.getIdForParameterSchema)(r,n,i,u.name),d=GR.Gateway.instance.schemaValidator[l],p=d(e[u.name]),m=(0,Ce.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Ce.validateParameters=JR;var zR=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");Ce.logErrors=zR;var WR=o(t=>t===Da.ValidationOptions.logOnly||t===Da.ValidationOptions.rejectAndLog,"shouldLog");Ce.shouldLog=WR;var QR=o(t=>t===Da.ValidationOptions.rejectOnly||t===Da.ValidationOptions.rejectAndLog,"shouldReject");Ce.shouldReject=QR;var YR=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");Ce.getErrorsFromValidator=YR});var r_=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.handleBodyValidation=void 0;var ZR=un(),XR=Lr(),Ua=ve(),eO=La(),Ke=Ti();async function tO(t,e,r){if(!r.validateBody||r.validateBody===XR.ValidationOptions.none)return;let n;try{n=await e.clone().json()}catch(f){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=Ua.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",y,[n],f),(0,Ke.shouldReject)(r.validateBody))return v}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Ua.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,eO.getIdForRequestBodySchema)(t.route.path,e.method,i),c=ZR.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Ua.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Ke.getErrorsFromValidator)(l),m=Ua.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",d,[n],p),(0,Ke.shouldReject)(r.validateBody))return m}o(tO,"handleBodyValidation");Ma.handleBodyValidation=tO});var n_=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.handleHeadersValidation=void 0;var rO=Lr(),nO=ve(),Si=Ti();function iO(t,e,r){if(!r.validateHeaders||r.validateHeaders===rO.ValidationOptions.none)return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,Si.getParametersForOperation)(t),s=(0,Si.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=nO.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Si.shouldLog)(r.validateHeaders)&&(0,Si.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Si.shouldReject)(r.validateHeaders))return c}}o(iO,"handleHeadersValidation");ka.handleHeadersValidation=iO});var i_=g(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.handlePathParameterValidation=void 0;var oO=Lr(),sO=ve(),Ii=Ti();function aO(t,e,r){if(!r.validatePathParameters||r.validatePathParameters===oO.ValidationOptions.none)return;let n=(0,Ii.getParametersForOperation)(t),i=(0,Ii.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=sO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ii.shouldLog)(r.validatePathParameters)&&(0,Ii.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ii.shouldReject)(r.validatePathParameters))return a}}o(aO,"handlePathParameterValidation");Fa.handlePathParameterValidation=aO});var o_=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.handleQueryParameterValidation=void 0;var cO=Lr(),uO=ve(),Ai=Ti();function lO(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters===cO.ValidationOptions.none)return;let n=(0,Ai.getParametersForOperation)(t),i=(0,Ai.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=uO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ai.shouldLog)(r.validateQueryParameters)&&(0,Ai.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ai.shouldReject)(r.validateQueryParameters))return a}}o(lO,"handleQueryParameterValidation");Ha.handleQueryParameterValidation=lO});var Lr=g(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy=Ft.ValidationOptions=void 0;var dO=r_(),pO=n_(),hO=i_(),fO=o_(),s_;(function(t){t.none="none",t.logOnly="log-only",t.rejectAndLog="reject-and-log",t.rejectOnly="reject-only"})(s_||(Ft.ValidationOptions=s_={}));var mO=o(async(t,e,r)=>{let n=(0,fO.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,hO.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,pO.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,dO.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");Ft.RequestValidationInboundPolicy=mO;Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy});var a_=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.RequireOriginInboundPolicy=void 0;var yO=ke(),gO=D(),_O=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new gO.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return yO.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");qa.RequireOriginInboundPolicy=_O});var c_=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.SetBodyInboundPolicy=void 0;var bO=ke(),EO=o(async(t,e,r)=>new bO.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");$a.SetBodyInboundPolicy=EO});var l_=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.SetHeadersInboundPolicy=void 0;var wO=ke(),u_=D(),vO=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new u_.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new u_.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new wO.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");ja.SetHeadersInboundPolicy=vO});var p_=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.SetHeadersOutboundPolicy=void 0;var d_=D(),TO=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new d_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new d_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Va.SetHeadersOutboundPolicy=TO});var f_=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.SetQueryParamsInboundPolicy=void 0;var SO=ke(),h_=D(),IO=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new h_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new h_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new SO.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Ga.SetQueryParamsInboundPolicy=IO});var m_=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetStatusOutboundPolicy=void 0;var AO=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Ba.SetStatusOutboundPolicy=AO});var y_=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SleepInboundPolicy=void 0;var PO=D(),RO=o(async t=>new Promise((r,n)=>{setTimeout(r,t)}),"sleep"),OO=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new PO.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await RO(r.sleepInMs),t},"SleepInboundPolicy");Ka.SleepInboundPolicy=OO});var __=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SupabaseJwtInboundPolicy=void 0;var xO=ke(),g_=D(),NO=ve(),CO=lr(),LO=Mt(),DO=o(async(t,e,r,n)=>{(0,CO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,LO.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof xO.ZuploRequest))throw new g_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new g_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?NO.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Ja.SupabaseJwtInboundPolicy=DO});var E_=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var UO=ur(),MO=_r(),b_=D(),kO=Ge(),FO=ys(),HO=lr(),qO=o(async(t,e,r,n)=>{(0,HO.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=new MO.MemoryZoneReadThroughCache((0,UO.getPolicyCacheName)(n),{logger:kO.SystemLogMap.getLogger(e)}),s=await i.get(n);if(!s){let a=await $O(r,e);i.put(n,a.access_token,a.expires_in-(r.expirationOffsetSeconds??300)),s=a.access_token}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");za.UpstreamAzureAdServiceAuthInboundPolicy=qO;async function $O(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,FO.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new b_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new b_.RuntimeError("Response returned from Azure AD is not in the expected format.")}o($O,"getAccessToken")});var v_=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var jO=ur(),VO=_r(),GO=D(),BO=Ge(),Yd=sn(),KO=lr(),w_="https://accounts.google.com/o/oauth2/token",Zd,JO=o(async(t,e,r,n)=>{(0,KO.optionValidator)(r,n).required("serviceAccountJson","string"),Zd||(Zd=await Yd.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=new VO.MemoryZoneReadThroughCache((0,jO.getPolicyCacheName)(n),{logger:BO.SystemLogMap.getLogger(e)}),a=await s.get(n);if(!a){let c=await(0,Yd.getTokenFromGcpServiceAccount)({serviceAccount:Zd,audience:w_,payload:i}),u=await(0,Yd.exchangeGgpJwtForIdToken)(w_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u.access_token)throw new GO.RuntimeError("Invalid OAuth response from Firebase");a=u.access_token,s.put(n,a,(u.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Wa.UpstreamFirebaseAdminAuthInboundPolicy=JO});var T_=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.sha256=void 0;async function zO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(zO,"sha256");Qa.sha256=zO});var S_=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.UpstreamFirebaseUserAuthInboundPolicy=void 0;var WO=ur(),QO=_r(),Nn=D(),YO=Ge(),ZO=T_(),Xd=sn(),XO=ta(),e0=lr(),t0="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",r0=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],ep,n0=o(async(t,e,r,n)=>{if((0,e0.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Nn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let d in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,d)){if(r0.indexOf(d)!==-1)throw new Nn.ConfigurationError(`Developer claim "${d}" is reserved and cannot be specified.`);i[d]=r.developerClaims[d]}}ep||(ep=await Xd.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new Nn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new Nn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,XO.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Nn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=new QO.MemoryZoneReadThroughCache((0,WO.getPolicyCacheName)(n),{logger:YO.SystemLogMap.getLogger(e)}),c={uid:s,claims:i},u=await(0,ZO.sha256)(JSON.stringify(c)),l=await a.get(u);if(!l){let d=await(0,Xd.getTokenFromGcpServiceAccount)({serviceAccount:ep,audience:t0,payload:c}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,m=await(0,Xd.exchangeFirebaseJwtForIdToken)(p,d,{retries:r.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new Nn.RuntimeError("Invalid token response from Firebase");l=m.idToken,a.put(u,l,(m.expiresIn?parseInt(m.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");Ya.UpstreamFirebaseUserAuthInboundPolicy=n0});var A_=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.UpstreamGcpJwtInboundPolicy=void 0;var I_=sn(),i0=lr(),tp,o0=o(async(t,e,r,n)=>{(0,i0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),tp||(tp=await I_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,I_.getTokenFromGcpServiceAccount)({serviceAccount:tp,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");Za.UpstreamGcpJwtInboundPolicy=o0});var O_=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.UpstreamGcpServiceAuthInboundPolicy=void 0;var P_=ur(),s0=Kc(),a0=_r(),c0=D(),rp=sn(),u0=lr(),R_="https://www.googleapis.com/oauth2/v4/token",np,l0=o(async(t,e,r,n)=>{(0,u0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),np||(np=await rp.GcpServiceAccount.init(r.serviceAccountJson));let i;r.useMemoryCacheOnly?i=new s0.MemoryCache((0,P_.getPolicyCacheName)(n)):i=new a0.MemoryZoneReadThroughCache((0,P_.getPolicyCacheName)(n),e);let s=await i.get(n);if(!s){let a=await(0,rp.getTokenFromGcpServiceAccount)({serviceAccount:np,audience:R_,payload:{target_audience:`${r.audience}`}}),{id_token:c}=await(0,rp.exchangeGgpJwtForIdToken)(R_,a,{retries:r.tokenRetries??3,retryDelayMs:10});if(!c)throw new c0.RuntimeError("Invalid token response from GCP");s=c,i.put(n,s,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamGcpServiceAuthInboundPolicy");Xa.UpstreamGcpServiceAuthInboundPolicy=l0});var N_=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ValidateJsonSchemaInbound=void 0;var d0=D(),x_=ve(),p0=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return x_.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new d0.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return x_.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");ec.ValidateJsonSchemaInbound=p0});var C_=g(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.serialize=dr.ContentTypes=void 0;dr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function h0(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(dr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(dr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(h0,"serialize");dr.serialize=h0});var L_=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.ServiceProviderImpl=void 0;var f0=D(),ip=class t{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,r){if(this.services.get(e))throw new f0.SystemError(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};tc.ServiceProviderImpl=ip});var D_=g(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var m0={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};op.default=m0});var ke=g(h=>{"use strict";var y0=h&&h.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),U_=h&&h.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&y0(e,t,r)},g0=h&&h.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(h,"__esModule",{value:!0});h.ReadmeMetricsInboundPolicy=h.RateLimitInboundPolicy=h.BasicRateLimitInboundPolicy=h.PropelAuthJwtInboundPolicy=h.OpenIdJwtInboundPolicy=h.OktaJwtInboundPolicy=h.setMoesifContext=h.MoesifInboundPolicy=h.MockApiInboundPolicy=h.JWTScopeValidationInboundPolicy=h.GeoFilterInboundPolicy=h.FormDataToJsonInboundPolicy=h.FirebaseJwtInboundPolicy=h.CompositeInboundPolicy=h.CognitoJwtInboundPolicy=h.ClerkJwtInboundPolicy=h.ClearHeadersOutboundPolicy=h.ClearHeadersInboundPolicy=h.ChangeMethodInboundPolicy=h.CachingInboundPolicy=h.BasicAuthInboundPolicy=h.Auth0JwtInboundPolicy=h.ApiKeyInboundPolicy=h.ApiAuthKeyInboundPolicy=h.AmberfloMeteringPolicy=h.AmberfloMeteringInboundPolicy=h.AuditLogPlugin=h.AuditLogDataStaxProvider=h.HttpStatusCode=h.webSocketPipelineHandler=h.webSocketHandler=h.urlRewriteHandler=h.urlForwardHandler=h.redirectHandler=h.openApiSpecHandler=h.awsLambdaHandler=h.AwsLambdaHandlerExtensions=h.purgeGatewayCache=h.Handler=h.originalFetch=h.ConfigurationError=h.isZuploReadableEnvVariableName=h.isRestrictedEnvVariableName=h.environment=h.ContextData=h.ResponseSentEvent=h.ResponseSendingEvent=h.VALID_COMPATIBILITY_DATES=h.ZoneCache=h.MemoryZoneReadThroughCache=void 0;h.sanitizedIdentifierName=h.getRawOperationDataIdentifierName=h.getIdForRequestBodySchema=h.getIdForRefSchema=h.getIdForParameterSchema=h.SystemLogMap=h.httpStatuses=h.SYSTEM_LOGGER=h.API_KEY=h.ServiceProviderImpl=h.serialize=h.ContentTypes=h.Router=h.LookupResult=h.SystemRouteName=h.ZuploRequest=h.ProblemResponseFormatter=h.HttpProblems=h.ValidateJsonSchemaInbound=h.UpstreamGcpServiceAuthInboundPolicy=h.UpstreamGcpJwtInboundPolicy=h.UpstreamFirebaseUserAuthInboundPolicy=h.UpstreamFirebaseAdminAuthInboundPolicy=h.UpstreamAzureAdServiceAuthInboundPolicy=h.SupabaseJwtInboundPolicy=h.SleepInboundPolicy=h.SetStatusOutboundPolicy=h.SetQueryParamsInboundPolicy=h.SetHeadersOutboundPolicy=h.SetHeadersInboundPolicy=h.SetBodyInboundPolicy=h.RequireOriginInboundPolicy=h.SchemaBasedRequestValidation=h.RequestValidationInboundPolicy=h.RequestSizeLimitInboundPolicy=h.ReplaceStringOutboundPolicy=h.RemoveQueryParamsInboundPolicy=h.RemoveHeadersOutboundPolicy=h.RemoveHeadersInboundPolicy=void 0;qp();var _0=_r();Object.defineProperty(h,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return _0.MemoryZoneReadThroughCache}});var b0=Wc();Object.defineProperty(h,"ZoneCache",{enumerable:!0,get:function(){return b0.ZoneCache}});var E0=jp();Object.defineProperty(h,"VALID_COMPATIBILITY_DATES",{enumerable:!0,get:function(){return E0.VALID_COMPATIBILITY_DATES}});var M_=wr();Object.defineProperty(h,"ResponseSendingEvent",{enumerable:!0,get:function(){return M_.ResponseSendingEvent}});Object.defineProperty(h,"ResponseSentEvent",{enumerable:!0,get:function(){return M_.ResponseSentEvent}});var w0=oy();Object.defineProperty(h,"ContextData",{enumerable:!0,get:function(){return w0.ContextData}});var sp=Xl();Object.defineProperty(h,"environment",{enumerable:!0,get:function(){return sp.environment}});Object.defineProperty(h,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return sp.isRestrictedEnvVariableName}});Object.defineProperty(h,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return sp.isZuploReadableEnvVariableName}});var v0=D();Object.defineProperty(h,"ConfigurationError",{enumerable:!0,get:function(){return v0.ConfigurationError}});var T0=td();Object.defineProperty(h,"originalFetch",{enumerable:!0,get:function(){return T0.originalFetch}});var k_=fy();Object.defineProperty(h,"Handler",{enumerable:!0,get:function(){return k_.Handler}});Object.defineProperty(h,"purgeGatewayCache",{enumerable:!0,get:function(){return k_.purgeGatewayCache}});var F_=Ny();Object.defineProperty(h,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return F_.AwsLambdaHandlerExtensions}});Object.defineProperty(h,"awsLambdaHandler",{enumerable:!0,get:function(){return F_.awsLambdaHandler}});var S0=Ly();Object.defineProperty(h,"openApiSpecHandler",{enumerable:!0,get:function(){return S0.openApiSpecHandler}});var I0=Dy();Object.defineProperty(h,"redirectHandler",{enumerable:!0,get:function(){return I0.redirectHandler}});var A0=My();Object.defineProperty(h,"urlForwardHandler",{enumerable:!0,get:function(){return A0.urlForwardHandler}});var P0=Fy();Object.defineProperty(h,"urlRewriteHandler",{enumerable:!0,get:function(){return P0.urlRewriteHandler}});var R0=qy();Object.defineProperty(h,"webSocketHandler",{enumerable:!0,get:function(){return R0.webSocketHandler}});var O0=Vy();Object.defineProperty(h,"webSocketPipelineHandler",{enumerable:!0,get:function(){return O0.webSocketPipelineHandler}});var x0=fu();Object.defineProperty(h,"HttpStatusCode",{enumerable:!0,get:function(){return x0.HttpStatusCode}});U_(Yy(),h);U_(eg(),h);var N0=tg();Object.defineProperty(h,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return N0.AuditLogDataStaxProvider}});var C0=ng();Object.defineProperty(h,"AuditLogPlugin",{enumerable:!0,get:function(){return C0.AuditLogPlugin}});var H_=lg();Object.defineProperty(h,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringInboundPolicy}});Object.defineProperty(h,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringPolicy}});var q_=fg();Object.defineProperty(h,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiAuthKeyInboundPolicy}});Object.defineProperty(h,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiKeyInboundPolicy}});var L0=mg();Object.defineProperty(h,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return L0.Auth0JwtInboundPolicy}});var D0=yg();Object.defineProperty(h,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return D0.BasicAuthInboundPolicy}});var U0=gg();Object.defineProperty(h,"CachingInboundPolicy",{enumerable:!0,get:function(){return U0.CachingInboundPolicy}});var M0=_g();Object.defineProperty(h,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return M0.ChangeMethodInboundPolicy}});var k0=bg();Object.defineProperty(h,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return k0.ClearHeadersInboundPolicy}});var F0=Eg();Object.defineProperty(h,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return F0.ClearHeadersOutboundPolicy}});var H0=wg();Object.defineProperty(h,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return H0.ClerkJwtInboundPolicy}});var q0=Tg();Object.defineProperty(h,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return q0.CognitoJwtInboundPolicy}});var $0=Ig();Object.defineProperty(h,"CompositeInboundPolicy",{enumerable:!0,get:function(){return $0.CompositeInboundPolicy}});var j0=Ag();Object.defineProperty(h,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return j0.FirebaseJwtInboundPolicy}});var V0=Pg();Object.defineProperty(h,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return V0.FormDataToJsonInboundPolicy}});var G0=Rg();Object.defineProperty(h,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return G0.GeoFilterInboundPolicy}});var B0=Og();Object.defineProperty(h,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return B0.JWTScopeValidationInboundPolicy}});var K0=Ng();Object.defineProperty(h,"MockApiInboundPolicy",{enumerable:!0,get:function(){return K0.MockApiInboundPolicy}});var $_=Mg();Object.defineProperty(h,"MoesifInboundPolicy",{enumerable:!0,get:function(){return $_.MoesifInboundPolicy}});Object.defineProperty(h,"setMoesifContext",{enumerable:!0,get:function(){return $_.setMoesifContext}});var J0=kg();Object.defineProperty(h,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return J0.OktaJwtInboundPolicy}});var z0=Mt();Object.defineProperty(h,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return z0.OpenIdJwtInboundPolicy}});var W0=Fg();Object.defineProperty(h,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return W0.PropelAuthJwtInboundPolicy}});var j_=Bg();Object.defineProperty(h,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});Object.defineProperty(h,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});var Q0=Wg();Object.defineProperty(h,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return Q0.ReadmeMetricsInboundPolicy}});var Y0=Qg();Object.defineProperty(h,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return Y0.RemoveHeadersInboundPolicy}});var Z0=Yg();Object.defineProperty(h,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return Z0.RemoveHeadersOutboundPolicy}});var X0=Zg();Object.defineProperty(h,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return X0.RemoveQueryParamsInboundPolicy}});var ex=Xg();Object.defineProperty(h,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return ex.ReplaceStringOutboundPolicy}});var tx=t_();Object.defineProperty(h,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return tx.RequestSizeLimitInboundPolicy}});var V_=Lr();Object.defineProperty(h,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return V_.RequestValidationInboundPolicy}});Object.defineProperty(h,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return V_.SchemaBasedRequestValidation}});var rx=a_();Object.defineProperty(h,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return rx.RequireOriginInboundPolicy}});var nx=c_();Object.defineProperty(h,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return nx.SetBodyInboundPolicy}});var ix=l_();Object.defineProperty(h,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return ix.SetHeadersInboundPolicy}});var ox=p_();Object.defineProperty(h,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return ox.SetHeadersOutboundPolicy}});var sx=f_();Object.defineProperty(h,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return sx.SetQueryParamsInboundPolicy}});var ax=m_();Object.defineProperty(h,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return ax.SetStatusOutboundPolicy}});var cx=y_();Object.defineProperty(h,"SleepInboundPolicy",{enumerable:!0,get:function(){return cx.SleepInboundPolicy}});var ux=__();Object.defineProperty(h,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return ux.SupabaseJwtInboundPolicy}});var lx=E_();Object.defineProperty(h,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return lx.UpstreamAzureAdServiceAuthInboundPolicy}});var dx=v_();Object.defineProperty(h,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return dx.UpstreamFirebaseAdminAuthInboundPolicy}});var px=S_();Object.defineProperty(h,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return px.UpstreamFirebaseUserAuthInboundPolicy}});var hx=A_();Object.defineProperty(h,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return hx.UpstreamGcpJwtInboundPolicy}});var fx=O_();Object.defineProperty(h,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return fx.UpstreamGcpServiceAuthInboundPolicy}});var mx=N_();Object.defineProperty(h,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return mx.ValidateJsonSchemaInbound}});var yx=ve();Object.defineProperty(h,"HttpProblems",{enumerable:!0,get:function(){return yx.HttpProblems}});var gx=oo();Object.defineProperty(h,"ProblemResponseFormatter",{enumerable:!0,get:function(){return gx.ProblemResponseFormatter}});var _x=Wn();Object.defineProperty(h,"ZuploRequest",{enumerable:!0,get:function(){return _x.ZuploRequest}});var bx=Sr();Object.defineProperty(h,"SystemRouteName",{enumerable:!0,get:function(){return bx.SystemRouteName}});var G_=Gl();Object.defineProperty(h,"LookupResult",{enumerable:!0,get:function(){return G_.LookupResult}});Object.defineProperty(h,"Router",{enumerable:!0,get:function(){return G_.Router}});var B_=C_();Object.defineProperty(h,"ContentTypes",{enumerable:!0,get:function(){return B_.ContentTypes}});Object.defineProperty(h,"serialize",{enumerable:!0,get:function(){return B_.serialize}});var Ex=L_();Object.defineProperty(h,"ServiceProviderImpl",{enumerable:!0,get:function(){return Ex.ServiceProviderImpl}});var K_=Tu();Object.defineProperty(h,"API_KEY",{enumerable:!0,get:function(){return K_.API_KEY}});Object.defineProperty(h,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return K_.SYSTEM_LOGGER}});var wx=D_();Object.defineProperty(h,"httpStatuses",{enumerable:!0,get:function(){return g0(wx).default}});var vx=Ge();Object.defineProperty(h,"SystemLogMap",{enumerable:!0,get:function(){return vx.SystemLogMap}});var Pi=La();Object.defineProperty(h,"getIdForParameterSchema",{enumerable:!0,get:function(){return Pi.getIdForParameterSchema}});Object.defineProperty(h,"getIdForRefSchema",{enumerable:!0,get:function(){return Pi.getIdForRefSchema}});Object.defineProperty(h,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Pi.getIdForRequestBodySchema}});Object.defineProperty(h,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Pi.getRawOperationDataIdentifierName}});Object.defineProperty(h,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Pi.sanitizedIdentifierName}})});var J_=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.BaseCryptoBeta=Cn.supportedDigests=void 0;Cn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var ap=class{static{o(this,"BaseCryptoBeta")}};Cn.BaseCryptoBeta=ap});var z_=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.WorkerCryptoBeta=void 0;var cp=J_(),Tx=D(),up=class extends cp.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!cp.supportedDigests.includes(e.toLowerCase()))throw new Tx.RuntimeError(`Algorithm ${e} is not supported. Try using ${cp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};rc.WorkerCryptoBeta=up});var W_=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.BaseKeyValueStore=void 0;var lp=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};nc.BaseKeyValueStore=lp});var Y_=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.WorkerKeyValueStore=void 0;var Q_=D(),Sx=W_(),dp=class extends Sx.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=globalThis.ZUPLO_KV;if(!n)throw new Q_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,r,n){if(typeof e!="string")throw new Q_.ConfigurationError("value must be of type string");return this.#e.put(e,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(e,r){return this.#e.get(e,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};ic.WorkerKeyValueStore=dp});var Ot=g(ct=>{"use strict";var Ix=ct&&ct.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ax=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ix(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Ax(ke(),ct);var Px=z_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Px.WorkerCryptoBeta}});var Rx=Y_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return Rx.WorkerKeyValueStore}})});var UN={};Gi(UN,{GraphQLComplexityLimitInboundPolicy:()=>Ob,GraphQLDisableIntrospectionInboundPolicy:()=>Nb});module.exports=Bi(UN);var Gn=Mp(Ot());function B(t,e){if(!!!t)throw new Error(e)}o(B,"devAssert");function be(t){return typeof t=="object"&&t!==null}o(be,"isObjectLike");function Tt(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(Tt,"invariant");var Ox=/\r\n|[\n\r]/g;function Ln(t,e){let r=0,n=1;for(let i of t.body.matchAll(Ox)){if(typeof i.index=="number"||Tt(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(Ln,"getLocation");function pp(t){return oc(t.source,Ln(t.source,t.start))}o(pp,"printLocation");function oc(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?r:0,u=e.column+c,l=`${t.name}:${a}:${u}
|
|
66
66
|
`,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let m=Math.floor(u/80),f=u%80,y=[];for(let v=0;v<p.length;v+=80)y.push(p.slice(v,v+80));return l+Z_([[`${a} |`,y[0]],...y.slice(1,m+1).map(v=>["|",v]),["|","^".padStart(f)],["|",y[m+1]]])}return l+Z_([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(oc,"printSourceLocation");function Z_(t){let e=t.filter(([n,i])=>i!==void 0),r=Math.max(...e.map(([n])=>n.length));return e.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
|
|
67
67
|
`)}o(Z_,"printPrefixedLines");function xx(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}o(xx,"toNormalizedOptions");var C=class t extends Error{static{o(this,"GraphQLError")}constructor(e,...r){var n,i,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=xx(r);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=X_(Array.isArray(a)?a:a?[a]:void 0);let m=X_((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(m==null||(i=m[0])===null||i===void 0?void 0:i.source),this.positions=u??m?.map(y=>y.start),this.locations=u&&c?u.map(y=>Ln(c,y)):m?.map(y=>Ln(y.source,y.start));let f=be(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??f)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(e+=`
|
|
68
68
|
|