@zuplo/runtime 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 CHANGED
@@ -59,5 +59,5 @@
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
60
  `)}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 E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=ir(await ai(this.body||""))}return e}};async function rt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?sr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,sr.encode(e))}s(rt,"hmac");async function ai(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?sr.encode(t):t)}s(ai,"hash");function ir(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(ir,"buf2hex");function ui(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ui,"encodeRfc3986");function Bu(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in si?[si[i],a]:[i,a]}s(Bu,"guessServiceRegion");function zu(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(zu,"b64ToUint6");function li(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=zu(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(li,"base64Decode");function $t(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s($t,"uint6ToB64");function di(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint($t(o>>>18&63),$t(o>>>12&63),$t(o>>>6&63),$t(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(di,"base64Encode");function Se(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Se,"numberToString");function Gu(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Se(Math.floor(n/60)),i=Se(n%60);return`${r}${o}${i}`}s(Gu,"getCLFOffset");function ur(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"],n=Se(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Se(t.getHours()),a=Se(t.getMinutes()),u=Se(t.getSeconds()),c=Gu(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(ur,"toCLFDate");var pi=(0,gi.debug)("zuplo:runtime"),Vu="X-Amzn-Trace-Id",ju="x-amzn-errortype",mi=[],Ju=s(async(t,e,n)=>{let r=n;for await(let o of mi)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Vu)??void 0,this.errorType=n.get(ju)??void 0}},fi={addSendingAwsLambdaEventHook:t=>{mi.push(t)}};async function hi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new Le({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(pi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,R]=await Qu(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,b;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?b=Yu(t,e):b=await Wu(t,e,{useAwsResourcePathStyle:u}),pi("Calling onSendingAwsLambdaEvent hook");let w=await Ju(t,e,b);w.body=p,w.isBase64Encoded=R;let P=await l.fetch(d,{body:JSON.stringify(w)});try{return Ku(P)}catch(O){if(O instanceof j){let C=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&O.traceId?{AMZN_TRACE_ID_HEADER:O.traceId}:void 0;return I.internalServerError(t,e,void 0,C)}throw O}}s(hi,"awsLambdaHandler");async function Ku(t){let e;try{e=await t.json()}catch{throw new j("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 j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(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 n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new j(`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 j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=li(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new j(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(Ku,"getResponse");async function Wu(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.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:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ur(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ec(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Wu,"buildEventVersion1");function Yu(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,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:r.hostname,domainPrefix:null,http:{method:t.method,path:r.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:ur(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(Yu,"buildEventVersion2");async function Qu(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Xu(e,o)){let i=await t.arrayBuffer();n=di(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(Qu,"getBodyResult");function Xu(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Xu,"matchesContentType");function ec(t,e=!1){if(!e)return t;let n=or(t),r=ii(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(ec,"getResourcePath");var tc=[502,503,504];async function _e(t,e){if(tc.includes(t.status)){let n=A.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(_e,"logBadGatewayResponses");var cr;function le(t){if(cr===void 0){let n=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),cr=n}return t.log[cr]}s(le,"getHandlerUserLogFunction");async function yi(t,e){let n=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=nc(i);if(!a.isValid)throw new f(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return I.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return _e(l,e),l}s(yi,"openApiSpecHandler");var nc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function bi(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(bi,"redirectHandler");function rc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(rc,"join");async function Ri(t,e){let n=le(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=rc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),_e(p,e),p}s(Ri,"urlForwardHandler");var oc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function wi(t,e){let n=le(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?oc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),_e(d,e),d}s(wi,"urlRewriteHandler");async function Pi(t,e){let n=y.instance,r=e.route.handler.options,o=le(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await ei(u),b=new URL(u);u=new URL(`${m.serviceBaseUrl}${b.pathname}${b.search}`).toString();for(let P in m.tunnelHeaders)p.set(P,m.tunnelHeaders[P])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Pi,"webSocketHandler");var lr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Ei=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ii(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{s(async u=>{let c=await Ei(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Ii,"wireUpListeners");async function xi(t,e){let n=y.instance,r=e.route.handler.options,o=le(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new f("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let O=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${O}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let b=l.webSocket;b.accept(),R.accept();let w=r.policies&&r.policies.inbound?lr(r.policies.inbound,"inbound"):[],P=r.policies&&r.policies.outbound?lr(r.policies.outbound,"outbound"):[];return Ii(R,b,t,e,w),Ii(b,R,t,e,P),new Response(null,{status:101,webSocket:p})}s(xi,"webSocketPipelineHandler");var Bt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new dr(this.options)}},dr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re($(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=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 T("dyna-trace-log-transport",10,this.#i)};var zt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new gr(this.options)}},pr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function ic(t,e){return btoa(`${t}:${e}`)}s(ic,"createBasicDigest");var gr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=ic(e.username,e.password),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new pr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:re($(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new T("loki-log-transport",10,this.#s)};var Gt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new mr(this.options)}},mr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re($(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
61
  `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new T("sumo-logic-log-transport",10,this.#s)};var sc="d3a5b78f-8236-48f5-b1df-4fe269d41172",Vt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new fr(this.options)}},fr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=zo(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=Jn(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${sc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new T("vmware-log-insights-log-transport",10,this.#s)};var jt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new hr(this.options)}},hr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("aws-log-transport",10,async e=>{if(e.length===0)return;let n=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:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Le({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:re($(r)),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(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var yr=new WeakMap,ac={tags:[]},Jt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new br(this.options)}static setContext(n,r){let o=yr.get(n);o||(o=ac);let i=Object.assign({...o},r);yr.set(n,i)}},br=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new T("data-dog-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(yr.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Rr(await r.text())}},Rr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var wr=new WeakMap,uc={dimensions:[]},Kt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Pr(this.options)}static setContext(n,r){let o=wr.get(n);o||(o=uc);let i=Object.assign({...o},r);wr.set(n,i)}},Pr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=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.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new T("dynatrace-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(wr.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Er(await r.text())}},Er=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Wt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Yt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Ir(e,this.#e,this.#t)}},vi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),cc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ir=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...cc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?vi(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?vi(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Oi=new Map;function Ti(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=Oi.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Oi.set(t,r),r}s(Ti,"statusCodesStringToNumberArray");function ye(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new E(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ye,"getValueFromRequestUser");var Ai=new WeakMap,Ci={},Qt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ai.set(e,n)}};async function Li(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Ti(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ai.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ye(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=Ci[n.apiKey];if(!R){let m=n.apiKey,b=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async w=>{try{let P=n.url??"https://app.amberflo.io/ingest",O=await fetch(P,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":b}});O.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${O.status}: ${await O.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),Ci[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Li,"AmberfloMeteringInboundPolicy");function M(t){return`zuplo-policy-${t}`}s(M,"getPolicyCacheName");var Si="key-metadata-cache-type";function lc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(lc,"getKeyValue");async function xr(t,e,n,r){if(!n.bucketName)if(nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=lc(a,o);if(!u||u==="")return i("No key present");let c=await dc(u),l=new q(M(r),{logger:A.getLogger(e)}),d=await l.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Si&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let p={key:u},R=await Oe({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(p)});if(R.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(R.status!==200){try{let w=await R.text(),P=JSON.parse(w);e.log.error("Unexpected response from key service",P)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${R.status}`)}let m=await R.json(),b={isValid:!0,typeId:Si,user:{sub:m.name,data:m.metadata}};return t.user=b.user,l.put(c,b,o.cacheTtlSeconds),t}s(xr,"ApiKeyInboundPolicy");async function dc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(dc,"hashValue");var _i=xr;var ot=require("jose");var vr={},pc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");vr[e.jwkUrl]||(vr[e.jwkUrl]=(0,ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ot.jwtVerify)(t,vr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),gc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?pc:gc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let b=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${b.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Di=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ki=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),b=n.accounts.find(w=>w.username===R&&w.password===m);return b||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var mc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function fc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(fc,"digestMessage");var hc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await fc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Hi(t,e,n,r){let o=await caches.open(`${M(r)}-${n.cacheId??""}`),i=n?.cacheHttpMethods?.map(c=>c.toUpperCase())??["GET"],a=await hc(t,n),u=await o.match(a);return u||(e.addEventListener("responseSent",c=>{try{let l=n.statusCodes??[200,206,301,302,303,404,410],d=c.response.clone();if(!l.includes(d.status)||!i.includes(t.method.toUpperCase()))return;let p=n?.expirationSecondsTtl??60,R=new Response(d.body,d);mc.forEach(m=>R.headers.delete(m)),R.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(o.put(a,R))}catch(l){e.log.error(`Error in caching-inbound-policy '${r}': "${l.message}"`,l)}}),t)}s(Hi,"CachingInboundPolicy");var Ui=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ni=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var Mi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Zi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qi=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Fi=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=V.instance,i=Ve(n.policies,o?.routeData.policies);return Bn(i)(t,e)},"CompositeInboundPolicy");function B(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' 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(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' 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 c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(B,"optionValidator");var $i=s(async(t,e,n,r)=>(B(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Bi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var De="__unknown__",zi=s(async(t,e,n,r)=>{let o={allow:{countries:He(n.allow?.countries,"allow.countries",r),regionCodes:He(n.allow?.regionCodes,"allow.regionCode",r),asns:He(n.allow?.asns,"allow.asOrganization",r)},block:{countries:He(n.block?.countries,"block.countries",r),regionCodes:He(n.block?.regionCodes,"block.regionCode",r),asns:He(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??De,a=e.incomingRequestProperties.regionCode?.toLowerCase()??De,u=e.incomingRequestProperties.asn?.toString()??De,c=o.ignoreUnknown&&i===De,l=o.ignoreUnknown&&a===De,d=o.ignoreUnknown&&u===De,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ke(t,e,r,i,a,u);let b=o.block.countries,w=o.block.regionCodes,P=o.block.asns;return b.length>0&&b.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?ke(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ke(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ke,"blockedResponse");function He(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(He,"toLowerStringArray");var Gi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ji=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Or(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Or(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Vi(a[u])}else return a.length>0?Vi(a[0]):Or(r,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");function Vi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.append("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Vi,"generateResponse");var Or=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var yc="Incoming",bc={logRequestBody:!0,logResponseBody:!0};function Ji(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ji,"headersToObject");function Ki(){return new Date().toISOString()}s(Ki,"timestamp");var Tr=new WeakMap,Rc={};function Qi(t,e){let n=Tr.get(t);n||(n=Rc);let r=Object.assign({...n},e);Tr.set(t,r)}s(Qi,"setMoesifContext");async function Wi(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(Wi,"readBody");var wc={},Cr;function Yi(){if(!Cr)throw new E("Invalid State - no _lastLogger");return Cr}s(Yi,"getLastLogger");function Pc(t){let e=wc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Yi().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Yi().error({status:o.status,body:await o.text()})})),e}s(Pc,"getDispatcher");async function Xi(t,e,n,r){Cr=e.log;let o=Ki(),i=Object.assign(bc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Wi(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Pc(i.applicationId),d=t.headers.get("true-client-ip"),p=Tr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ji(t.headers)},m=i.logResponseBody?await Wi(u,e):void 0,b={time:Ki(),status:u.status,headers:Ji(u.headers),body:m},w={request:R,response:b,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:yc};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(Xi,"MoesifInboundPolicy");var es=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ts=require("jose");var Ar,ns=s(async(t,e,n,r)=>{if(!Ar)try{Ar=await(0,ts.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Ar,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var os=Re(me());var Xt=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Lr=class extends Xt{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Sr=class extends Xt{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Ec(t,e){if(Fo(t))throw new Lr(e)}s(Ec,"throwIfUndefinedOrNull");function it(t,e){if(Ec(t,e),!We(t))throw new Sr(e,"string")}s(it,"throwIfNotString");var en=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return it(e,"redisClientUrl"),it(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){it(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},tn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(it(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var nn=(0,os.debug)("zuplo:policies:RateLimitInboundPolicy"),Ic="strict",xc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),vc=s(async t=>({key:`ip-${xc(t)}`}),"getIP"),Oc=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Tc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),rn;function Cc(t,e){let n;if(rn)return rn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new tn,rn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!We(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!We(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=en.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return rn=n,n}s(Cc,"getRedisClient");async function rs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(rs,"getCountAndUpdateExpiry");function Ac(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Ac,"wrapUserFunction");var Lc="Retry-After",_r=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Lc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Ac(n,r),user:Oc,ip:vc,all:Tc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",w=Cc(r,i),O=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ic)==="async"){let L=new oe(M(r),{logger:A.getLogger(e)}),J=rs(O,m,w,i,e.requestId),Z=await L.get(O);if(Z!==void 0&&Z<=Date.now()){nn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let K=Math.round((Z-Date.now())/1e3);return u(b,K)}return e.addEventListener("responseSending",K=>{try{let pe=K,mn=pe.mutableResponse;pe.mutableResponse=(async()=>{let be=await J;if(be.count>R){let Ms=Date.now()+be.ttlSeconds*1e3;return L.put(O,Ms,be.ttlSeconds).catch(Fr=>{throw i.error(Fr),Fr}),nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),u(b,be.ttlSeconds)}return mn})()}catch(pe){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,pe)}}),t}let D=await rs(O,m,w,i,e.requestId);return D.count>R?(nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (strict mode)`),u(b,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;nn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Dr;function is(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(is,"headersToNameValuePairs");function Sc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Sc,"queryToNameValueParis");function _c(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(_c,"parseIntOrUndefined");var ss={};async function as(t,e,n,r){let o=new Date,i=Date.now();return Dr||(Dr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?ye(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?ye(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Dr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:is(t.headers),queryString:Sc(t.query)},response:{status:a.status,statusText:a.statusText,headers:is(a.headers),content:{size:_c(t.headers.get("content-length"))}}}]}}},d=ss[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",b=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});b.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${b.status}: '${await b.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),ss[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(as,"ReadmeMetricsInboundPolicy");var us=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var cs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ls=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ds=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ps=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),gs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ps():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ps():t},"RequestSizeLimitInboundPolicy");function ms(t,e,n){return`_${de(t+"_"+e+"_"+n)}`}s(ms,"getRawOperationDataIdentifierName");function on(t,e,n,r){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(on,"getIdForParameterSchema");function sn(t,e,n){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${de(n.toLowerCase())}`}s(sn,"getIdForRequestBodySchema");function fs(t,e){return`_${de(t)}__${de(e)}`}s(fs,"getIdForRefSchema");function de(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(de,"sanitizedIdentifierName");var Ue=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Ne=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=on(n,r,o,c.name),d=V.instance.schemaValidator[l],p=d(e[c.name]),R=kr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),kr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let b=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=I.badRequest(e,t,{detail:`${b}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",b,[r],m),X(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,b=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?b:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=sn(t.route.path,e.method,o),u=V.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?b:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=kr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(hs,"handleBodyValidation");function ys(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ue(t),i=Ne(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(ys,"handleHeadersValidation");function bs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(bs,"handlePathParameterValidation");function Rs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(Rs,"handleQueryParameterValidation");var Hr=s(async(t,e,n)=>{let r=Rs(e,t,n);if(r!==void 0||(r=bs(e,t,n),r!==void 0)||(r=ys(e,t,n),r!==void 0))return r;let o=await hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),ws=Hr;var Ps=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Es=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Is=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var xs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Os=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Dc=s(async t=>new Promise((n,r)=>{setTimeout(n,t)}),"sleep"),Ts=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Dc(n.sleepInMs),t},"SleepInboundPolicy");var Cs=s(async(t,e,n,r)=>{B(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var As=s(async(t,e,n,r)=>{B(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=new q(M(r),{logger:A.getLogger(e)}),i=await o.get(r);if(!i){let a=await kc(n,e);o.put(r,a.access_token,a.expires_in-(n.expirationOffsetSeconds??300)),i=a.access_token}return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function kc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Oe({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:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(kc,"getAccessToken");var Ls="https://accounts.google.com/o/oauth2/token",Ur,Ss=s(async(t,e,n,r)=>{B(n,r).required("serviceAccountJson","string"),Ur||(Ur=await G.init(n.serviceAccountJson));let o={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(" ")},i=new q(M(r),{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await ee({serviceAccount:Ur,audience:Ls,payload:o}),c=await Ct(Ls,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c.access_token)throw new E("Invalid OAuth response from Firebase");a=c.access_token,i.put(r,a,(c.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");async function _s(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(_s,"sha256");var Hc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Uc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Nr,Ds=s(async(t,e,n,r)=>{if(B(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(Uc.indexOf(d)!==-1)throw new f(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}Nr||(Nr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ye(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=new q(M(r),{logger:A.getLogger(e)}),u={uid:i,claims:o},c=await _s(JSON.stringify(u)),l=await a.get(c);if(!l){let d=await ee({serviceAccount:Nr,audience:Hc,payload:u}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,R=await Go(p,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!R.idToken)throw new E("Invalid token response from Firebase");l=R.idToken,a.put(c,l,(R.expiresIn?parseInt(R.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Mr,ks=s(async(t,e,n,r)=>{B(n,r).required("audience","string").required("serviceAccountJson","string"),Mr||(Mr=await G.init(n.serviceAccountJson));let o=await ee({serviceAccount:Mr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Hs="https://www.googleapis.com/oauth2/v4/token",Zr,Us=s(async(t,e,n,r)=>{B(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Zr||(Zr=await G.init(n.serviceAccountJson));let o;n.useMemoryCacheOnly?o=new we(M(r)):o=new q(M(r),e);let i=await o.get(r);if(!i){let a=await ee({serviceAccount:Zr,audience:Hs,payload:{target_audience:`${n.audience}`}}),{id_token:u}=await Ct(Hs,a,{retries:n.tokenRetries??3,retryDelayMs:10});if(!u)throw new E("Invalid token response from GCP");i=u,o.put(r,i,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Ns=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var un={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ft(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(un.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(un.Json)||!e?JSON.stringify(t):t}s(ft,"serialize");var cn=class t{static{s(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,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Nc={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"},bt=Nc;var qr=["sha-1","sha-256","sha-384","sha-512"],ln=class{static{s(this,"BaseCryptoBeta")}};var dn=class extends ln{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!qr.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${qr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var pn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var gn=class extends pn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new st("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
62
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Er(await r.text())}},Er=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Wt=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Yt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Ir(e,this.#e,this.#t)}},vi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),cc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ir=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...cc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?vi(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?vi(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Oi=new Map;function Ti(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=Oi.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Oi.set(t,r),r}s(Ti,"statusCodesStringToNumberArray");function ye(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new E(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ye,"getValueFromRequestUser");var Ai=new WeakMap,Ci={},Qt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ai.set(e,n)}};async function Li(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Ti(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ai.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ye(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},R=Ci[n.apiKey];if(!R){let m=n.apiKey,b=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async w=>{try{let P=n.url??"https://app.amberflo.io/ingest",O=await fetch(P,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":b}});O.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${O.status}: ${await O.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),Ci[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Li,"AmberfloMeteringInboundPolicy");function M(t){return`zuplo-policy-${t}`}s(M,"getPolicyCacheName");var Si="key-metadata-cache-type";function lc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(lc,"getKeyValue");async function xr(t,e,n,r){if(!n.bucketName)if(nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=lc(a,o);if(!u||u==="")return i("No key present");let c=await dc(u),l=new q(M(r),{logger:A.getLogger(e)}),d=await l.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Si&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let p={key:u},R=await Oe({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(p)});if(R.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(R.status!==200){try{let w=await R.text(),P=JSON.parse(w);e.log.error("Unexpected response from key service",P)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${R.status}`)}let m=await R.json(),b={isValid:!0,typeId:Si,user:{sub:m.name,data:m.metadata}};return t.user=b.user,l.put(c,b,o.cacheTtlSeconds),t}s(xr,"ApiKeyInboundPolicy");async function dc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(dc,"hashValue");var _i=xr;var ot=require("jose");var vr={},pc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");vr[e.jwkUrl]||(vr[e.jwkUrl]=(0,ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ot.jwtVerify)(t,vr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),gc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?pc:gc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let b=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${b.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Di=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ki=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),b=n.accounts.find(w=>w.username===R&&w.password===m);return b||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var mc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function fc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(fc,"digestMessage");var hc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await fc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Hi(t,e,n,r){let o=await caches.open(`${M(r)}-${n.cacheId??""}`),i=n?.cacheHttpMethods?.map(c=>c.toUpperCase())??["GET"],a=await hc(t,n),u=await o.match(a);return u||(e.addEventListener("responseSent",c=>{try{let l=n.statusCodes??[200,206,301,302,303,404,410],d=c.response.clone();if(!l.includes(d.status)||!i.includes(t.method.toUpperCase()))return;let p=n?.expirationSecondsTtl??60,R=new Response(d.body,d);mc.forEach(m=>R.headers.delete(m)),R.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(o.put(a,R))}catch(l){e.log.error(`Error in caching-inbound-policy '${r}': "${l.message}"`,l)}}),t)}s(Hi,"CachingInboundPolicy");var Ui=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ni=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new _(t,{headers:o})},"ClearHeadersInboundPolicy");var Mi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Zi=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qi=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Fi=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=V.instance,i=Ve(n.policies,o?.routeData.policies);return Bn(i)(t,e)},"CompositeInboundPolicy");function B(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' 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(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' 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 c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(B,"optionValidator");var $i=s(async(t,e,n,r)=>(B(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Bi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var De="__unknown__",zi=s(async(t,e,n,r)=>{let o={allow:{countries:He(n.allow?.countries,"allow.countries",r),regionCodes:He(n.allow?.regionCodes,"allow.regionCode",r),asns:He(n.allow?.asns,"allow.asOrganization",r)},block:{countries:He(n.block?.countries,"block.countries",r),regionCodes:He(n.block?.regionCodes,"block.regionCode",r),asns:He(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??De,a=e.incomingRequestProperties.regionCode?.toLowerCase()??De,u=e.incomingRequestProperties.asn?.toString()??De,c=o.ignoreUnknown&&i===De,l=o.ignoreUnknown&&a===De,d=o.ignoreUnknown&&u===De,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ke(t,e,r,i,a,u);let b=o.block.countries,w=o.block.regionCodes,P=o.block.asns;return b.length>0&&b.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?ke(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ke(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ke,"blockedResponse");function He(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(He,"toLowerStringArray");var Gi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ji=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Or(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Or(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Vi(a[u])}else return a.length>0?Vi(a[0]):Or(r,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");function Vi(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Vi,"generateResponse");var Or=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var yc="Incoming",bc={logRequestBody:!0,logResponseBody:!0};function Ji(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ji,"headersToObject");function Ki(){return new Date().toISOString()}s(Ki,"timestamp");var Tr=new WeakMap,Rc={};function Qi(t,e){let n=Tr.get(t);n||(n=Rc);let r=Object.assign({...n},e);Tr.set(t,r)}s(Qi,"setMoesifContext");async function Wi(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(Wi,"readBody");var wc={},Cr;function Yi(){if(!Cr)throw new E("Invalid State - no _lastLogger");return Cr}s(Yi,"getLastLogger");function Pc(t){let e=wc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Yi().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Yi().error({status:o.status,body:await o.text()})})),e}s(Pc,"getDispatcher");async function Xi(t,e,n,r){Cr=e.log;let o=Ki(),i=Object.assign(bc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Wi(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Pc(i.applicationId),d=t.headers.get("true-client-ip"),p=Tr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ji(t.headers)},m=i.logResponseBody?await Wi(u,e):void 0,b={time:Ki(),status:u.status,headers:Ji(u.headers),body:m},w={request:R,response:b,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:yc};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(Xi,"MoesifInboundPolicy");var es=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ts=require("jose");var Ar,ns=s(async(t,e,n,r)=>{if(!Ar)try{Ar=await(0,ts.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Ar,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var os=Re(me());var Xt=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Lr=class extends Xt{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Sr=class extends Xt{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Ec(t,e){if(Fo(t))throw new Lr(e)}s(Ec,"throwIfUndefinedOrNull");function it(t,e){if(Ec(t,e),!We(t))throw new Sr(e,"string")}s(it,"throwIfNotString");var en=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return it(e,"redisClientUrl"),it(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){it(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},tn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(it(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var nn=(0,os.debug)("zuplo:policies:RateLimitInboundPolicy"),Ic="strict",xc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),vc=s(async t=>({key:`ip-${xc(t)}`}),"getIP"),Oc=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Tc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),rn;function Cc(t,e){let n;if(rn)return rn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new tn,rn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!We(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!We(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=en.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return rn=n,n}s(Cc,"getRedisClient");async function rs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(rs,"getCountAndUpdateExpiry");function Ac(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Ac,"wrapUserFunction");var Lc="Retry-After",_r=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Lc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Ac(n,r),user:Oc,ip:vc,all:Tc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",w=Cc(r,i),O=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Ic)==="async"){let L=new oe(M(r),{logger:A.getLogger(e)}),J=rs(O,m,w,i,e.requestId),Z=await L.get(O);if(Z!==void 0&&Z<=Date.now()){nn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let K=Math.round((Z-Date.now())/1e3);return u(b,K)}return e.addEventListener("responseSending",K=>{try{let pe=K,mn=pe.mutableResponse;pe.mutableResponse=(async()=>{let be=await J;if(be.count>R){let Ms=Date.now()+be.ttlSeconds*1e3;return L.put(O,Ms,be.ttlSeconds).catch(Fr=>{throw i.error(Fr),Fr}),nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),u(b,be.ttlSeconds)}return mn})()}catch(pe){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,pe)}}),t}let D=await rs(O,m,w,i,e.requestId);return D.count>R?(nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (strict mode)`),u(b,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;nn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Dr;function is(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(is,"headersToNameValuePairs");function Sc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Sc,"queryToNameValueParis");function _c(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(_c,"parseIntOrUndefined");var ss={};async function as(t,e,n,r){let o=new Date,i=Date.now();return Dr||(Dr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?ye(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?ye(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Dr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:is(t.headers),queryString:Sc(t.query)},response:{status:a.status,statusText:a.statusText,headers:is(a.headers),content:{size:_c(t.headers.get("content-length"))}}}]}}},d=ss[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",b=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});b.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${b.status}: '${await b.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),ss[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(as,"ReadmeMetricsInboundPolicy");var us=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var cs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var ls=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ds=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ps=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),gs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ps():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ps():t},"RequestSizeLimitInboundPolicy");function ms(t,e,n){return`_${de(t+"_"+e+"_"+n)}`}s(ms,"getRawOperationDataIdentifierName");function on(t,e,n,r){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(on,"getIdForParameterSchema");function sn(t,e,n){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${de(n.toLowerCase())}`}s(sn,"getIdForRequestBodySchema");function fs(t,e){return`_${de(t)}__${de(e)}`}s(fs,"getIdForRefSchema");function de(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(de,"sanitizedIdentifierName");var Ue=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Ne=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=on(n,r,o,c.name),d=V.instance.schemaValidator[l],p=d(e[c.name]),R=kr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),kr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let b=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=I.badRequest(e,t,{detail:`${b}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",b,[r],m),X(n.validateBody))return w}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,b=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?b:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=sn(t.route.path,e.method,o),u=V.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?b:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=kr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(hs,"handleBodyValidation");function ys(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ue(t),i=Ne(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(ys,"handleHeadersValidation");function bs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(bs,"handlePathParameterValidation");function Rs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(Rs,"handleQueryParameterValidation");var Hr=s(async(t,e,n)=>{let r=Rs(e,t,n);if(r!==void 0||(r=bs(e,t,n),r!==void 0)||(r=ys(e,t,n),r!==void 0))return r;let o=await hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),ws=Hr;var Ps=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Es=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Is=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var xs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var Os=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Dc=s(async t=>new Promise((n,r)=>{setTimeout(n,t)}),"sleep"),Ts=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Dc(n.sleepInMs),t},"SleepInboundPolicy");var Cs=s(async(t,e,n,r)=>{B(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var As=s(async(t,e,n,r)=>{B(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=new q(M(r),{logger:A.getLogger(e)}),i=await o.get(r);if(!i){let a=await kc(n,e);o.put(r,a.access_token,a.expires_in-(n.expirationOffsetSeconds??300)),i=a.access_token}return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function kc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Oe({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:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(kc,"getAccessToken");var Ls="https://accounts.google.com/o/oauth2/token",Ur,Ss=s(async(t,e,n,r)=>{B(n,r).required("serviceAccountJson","string"),Ur||(Ur=await G.init(n.serviceAccountJson));let o={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(" ")},i=new q(M(r),{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await ee({serviceAccount:Ur,audience:Ls,payload:o}),c=await Ct(Ls,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c.access_token)throw new E("Invalid OAuth response from Firebase");a=c.access_token,i.put(r,a,(c.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");async function _s(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(_s,"sha256");var Hc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Uc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Nr,Ds=s(async(t,e,n,r)=>{if(B(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(Uc.indexOf(d)!==-1)throw new f(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}Nr||(Nr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ye(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=new q(M(r),{logger:A.getLogger(e)}),u={uid:i,claims:o},c=await _s(JSON.stringify(u)),l=await a.get(c);if(!l){let d=await ee({serviceAccount:Nr,audience:Hc,payload:u}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,R=await Go(p,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!R.idToken)throw new E("Invalid token response from Firebase");l=R.idToken,a.put(c,l,(R.expiresIn?parseInt(R.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Mr,ks=s(async(t,e,n,r)=>{B(n,r).required("audience","string").required("serviceAccountJson","string"),Mr||(Mr=await G.init(n.serviceAccountJson));let o=await ee({serviceAccount:Mr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Hs="https://www.googleapis.com/oauth2/v4/token",Zr,Us=s(async(t,e,n,r)=>{B(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Zr||(Zr=await G.init(n.serviceAccountJson));let o;n.useMemoryCacheOnly?o=new we(M(r)):o=new q(M(r),e);let i=await o.get(r);if(!i){let a=await ee({serviceAccount:Zr,audience:Hs,payload:{target_audience:`${n.audience}`}}),{id_token:u}=await Ct(Hs,a,{retries:n.tokenRetries??3,retryDelayMs:10});if(!u)throw new E("Invalid token response from GCP");i=u,o.put(r,i,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Ns=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new S("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var un={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ft(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(un.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(un.Json)||!e?JSON.stringify(t):t}s(ft,"serialize");var cn=class t{static{s(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,n){if(this.services.get(e))throw new S(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Nc={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"},bt=Nc;var qr=["sha-1","sha-256","sha-384","sha-512"],ln=class{static{s(this,"BaseCryptoBeta")}};var dn=class extends ln{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!qr.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${qr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var pn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var gn=class extends pn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new st("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
63
63
  /*! For license information please see index.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1533.0",
3
+ "version": "5.1535.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {