@zuplo/graphql 5.1718.0 → 5.1720.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
@@ -71,7 +71,7 @@ Signature verification is impossible without access to the original signed mater
71
71
  `+d}):new kr.StripeSignatureVerificationError(t,e,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
72
72
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
73
73
  `+l+`
74
- `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new kr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}s(eR,"validateComputedSignature");function tR(e,t){return typeof e!="string"?null:e.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===t&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}s(tR,"parseHeader");function rR(e,t){if(e.length!==t.length)return!1;let r=e.length,n=0;for(let i=0;i<r;++i)n|=e.charCodeAt(i)^t.charCodeAt(i);return n===0}s(rR,"secureCompare");async function Fg(e,t){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(e)),o=new Uint8Array(i),a=new Array(o.length);for(let c=0;c<o.length;c++)a[c]=ip[o[c]];return a.join("")}s(Fg,"computeHMACSignatureAsync");Nn.computeHMACSignatureAsync=Fg;var ip=new Array(256);for(let e=0;e<ip.length;e++)ip[e]=e.toString(16).padStart(2,"0")});var qt=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.optionValidator=void 0;var Ai=L();function nR(e,t){let r=s((o,a,c)=>{let u=e[o];if(!(c&&u===void 0)){if(u===void 0)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=s((o,a)=>(r(o,a,!0),{optional:n,required:i}),"optional"),i=s((o,a)=>(r(o,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}s(nR,"optionValidator");da.optionValidator=nR});var op=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.StripeWebhookVerificationInboundPolicy=void 0;var iR=se(),oR=qg(),sR=qt(),aR=s(async(e,t,r,n)=>{(0,sR.optionValidator)(r,n).required("signingSecret","string").optional("tolerance","number");let i=e.headers.get("stripe-signature");try{let o=await e.clone().text();await(0,oR.constructEventAsync)(o,i,r.signingSecret)}catch(o){return t.log.error("Error validating stripe webhook",o),iR.HttpProblems.badRequest(e,t,{title:"Webhook Error",detail:o.message})}return e},"StripeWebhookVerificationInboundPolicy");pa.StripeWebhookVerificationInboundPolicy=aR});var $g=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.MeteringPlugin=void 0;var cR=gt(),sp=class extends cR.SystemRuntimePlugin{static{s(this,"MeteringPlugin")}};ha.MeteringPlugin=sp});var Vg=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.StripeMeteringPlugin=void 0;var jg=yn(),lt=L(),uR=Ct(),lR=op(),xn=se(),dR=Yt(),pR=zr(),hR=Uu(),fR=ot(),ap=Y(),cp=Dt(),mR=$g(),yR="checkout.session.completed",up=class extends mR.MeteringPlugin{static{s(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=s(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l}=this.options;if(!l)if(jg.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=jg.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new lt.ConfigurationError("StripeMeteringPlugin - No 'meteringBucketId' property provided");let d=this.options.meteringBucketRegion??"us-central1";if(!wR(d))throw new lt.ConfigurationError(`StripeMeteringPlugin - The value '${d}' on the property 'meteringBucketRegion' is invalid.`);let p=await c.json();if(!ER(p))return xn.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});u.log.info(`Received Stripe webhook event of type '${p.type}' with ID '${p.id}'.`);let m;try{m=await gR({event:p,stripeSecretKey:this.options.stripeSecretKey,logger:u.log})}catch(h){return xn.HttpProblems.internalServerError(c,u,{detail:h.message??"Unknown error getting subscription info"})}if(m){let h;if(this.options.apiKeyBucketName&&ap.Environment.instance.build.ACCOUNT_NAME&&this.options.zuploAccountApiKey?h=await bR({bucketName:this.options.apiKeyBucketName,accountName:ap.Environment.instance.build.ACCOUNT_NAME,stripeProductId:m.productId,stripeSubscriptionId:m.subscriptionId,stripeCustomerId:m.customerId,managerEmail:m.customerEmail,zuploAccountApiKey:this.options.zuploAccountApiKey,logger:u.log}):u.log.debug("Skipping consumer creation. No 'apiKeyBucketName', 'zuploAccountApiKey', or account variable set."),!h)return xn.HttpProblems.internalServerError(c,u,{detail:"No consumer was created, skipping creation of subscription"});let y="routes.oas.json";return _R({request:c,context:u,stripeProductId:m.productId,stripeSubscriptionId:m.subscriptionId,customerKey:h,productKey:y,meteringBucketId:l,meteringBucketRegion:d})}return xn.HttpProblems.ok(c,u,{detail:"Event was ignored by Stripe metering plugin webhook."})},"stripeWebhookHandler"),i=(0,pR.createInternalPolicyProcessor)({inboundPolicies:[{handler:lR.StripeWebhookVerificationInboundPolicy,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),o=new uR.Pipeline({processors:[dR.metricsProcessor,i],handler:n,gateway:r}),a=new fR.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:hR.SystemRouteName.StripePlugin});t.addRoute(a,o.execute)}};fa.StripeMeteringPlugin=up;async function gR({event:e,stripeSecretKey:t,logger:r}){let n;if(e.type===yR){let l=e,d=l.data?.object?.subscription;if(!d)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");if(!l.data?.object?.client_reference_id)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");let m=await fetch(`https://api.stripe.com/v1/subscriptions/${d}`,{headers:{Authorization:`Bearer ${t}`}}),h=await m.json();if(m.status!==200){let y="Error retrieving subscription from Stripe API.";throw r.error(y,h),new lt.RuntimeError(y)}n=h}if(!n)return;let i=n.id;if(!i)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");let o=n.items?.data.find(l=>l.object==="subscription_item");if(!o||!o.id)throw new Error("Invalid Stripe Webhook event. Expected '.data.object.items.data[]' to contain a subscription_item.");let a=o.plan;if(!a||!a.product)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.items.data[].plan'.");let c=await fetch(`https://api.stripe.com/v1/customers/${n.customer}`,{headers:{Authorization:`Bearer ${t}`}}),u=await c.json();if(c.status!==200){let l="Error retrieving customer from Stripe API.";throw r.error(l,u),new lt.RuntimeError(l)}return{subscriptionId:i,productId:a.product,customerId:n.customer,customerEmail:u.email}}s(gR,"getStripeSubscription");async function bR({accountName:e,bucketName:t,zuploAccountApiKey:r,stripeSubscriptionId:n,stripeProductId:i,stripeCustomerId:o,managerEmail:a,logger:c}){let u=new URL(`/v1/accounts/${e}/key-buckets/${t}/consumers`,"https://dev.zuplo.com");u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:`Consumer for Stripe subscription ${n}`,tags:{providerSubscriptionKey:n,planProviderKey:i},metadata:{stripeSubscriptionId:n,stripeProductId:i,stripeCustomerId:o},managers:[a]},p=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw c.error(h,m),new lt.RuntimeError(h)}return c.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:n,stripeProductId:i}),l}s(bR,"createConsumer");async function _R({request:e,context:t,stripeSubscriptionId:r,stripeProductId:n,customerKey:i,productKey:o,meteringBucketId:a,meteringBucketRegion:c}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:c,providerKey:r,planProviderKey:n,customerKey:i,productKey:o};try{let{authApiJWT:l,meteringServiceUrl:d}=ap.Environment.instance;if(!(0,cp.isNonEmptyString)(l))throw new lt.SystemError("No Zuplo JWT token set.");let p=await fetch(`${d}/internal/v1/metering/${a}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(u)});if(!p.ok){let m="Error creating metering subscription.",h;try{h=await p.json()}catch{h={status:p.status,statusText:p.statusText}}throw t.log.error(m,h),new lt.RuntimeError(m)}}catch(l){return xn.HttpProblems.internalServerError(e,t,{detail:l.message})}return t.log.info("Successfully created/updated metering subscription.",u),xn.HttpProblems.ok(e,t)}s(_R,"saveSubscription");function ER(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,cp.isString)(e.id)&&"type"in e&&(0,cp.isString)(e.type)}s(ER,"isStripeWebhookEvent");function wR(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}s(wR,"isMetricsRegion")});var zg=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.AmberfloMeteringInboundPolicy=Cn.AmberfloMeteringPolicy=void 0;var Gg=L(),vR=ve(),Bg=ii(),Jg=new WeakMap,Kg={},lp=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){Jg.set(t,r)}};Cn.AmberfloMeteringPolicy=lp;async function TR(e,t,r,n){if(!r.statusCodes)throw new Gg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,Bg.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async o=>{if(i.includes(o.status)){let a=Jg.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new Gg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,Bg.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},m=Kg[r.apiKey];if(!m){let h=r.apiKey,y=e.headers.get("zm-test-id")??"";m=new vR.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),Kg[h]=m}m.enqueue(p),t.waitUntil(m.waitUntilFlushed())}}),e}s(TR,"AmberfloMeteringInboundPolicy");Cn.AmberfloMeteringInboundPolicy=TR});var dp=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.sha256=void 0;async function SR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}s(SR,"sha256");ma.sha256=SR});var $t=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.getPolicyCacheName=void 0;var IR=dp(),Wg=new Map;async function PR(e,t){let r,n=Wg.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,IR.sha256)(JSON.stringify({policyName:e,options:t}))}`,Wg.set(e,r)),r}s(PR,"getPolicyCacheName");ya.getPolicyCacheName=PR});var mp=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.ApiKeyInboundPolicy=void 0;var AR=$t(),RR=Jt(),Qg=yn(),pp=L(),OR=Lt(),hp=Le(),fp=Y(),NR=Is(),Yg="key-metadata-cache-type";function xR(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}s(xR,"getKeyValue");async function CR(e,t,r,n){if(!r.bucketName)if(Qg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=Qg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new pp.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new pp.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let o=s(T=>i.allowUnauthenticatedRequests?e:OR.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return o("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return o("Invalid Authorization Scheme");let c=xR(a,i);if(!c||c==="")return o("No key present");let u=await LR(c),l=await(0,AR.getPolicyCacheName)(n,i),d=new RR.MemoryZoneReadThroughCache(l,{logger:hp.SystemLogMap.getLogger(t)}),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==Yg&&hp.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),o("Authorization Failed");let m={key:c},h=await(0,NR.fetchRetry)({retryDelayMs:5,retries:2,logger:hp.SystemLogMap.getLogger(t)},`${fp.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":fp.Environment.instance.deploymentName??"unknown","User-Agent":fp.Environment.instance.systemUserAgent},body:JSON.stringify(m)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),o("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new pp.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),v={isValid:!0,typeId:Yg,user:{sub:y.name,data:y.metadata}};return e.user=v.user,d.put(u,v,i.cacheTtlSeconds),e}s(CR,"ApiKeyInboundPolicy");ga.ApiKeyInboundPolicy=CR;async function LR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(LR,"hashValue")});var Zg=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ApiAuthKeyInboundPolicy=void 0;var DR=mp();ba.ApiAuthKeyInboundPolicy=DR.ApiKeyInboundPolicy});var jt=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.OpenIdJwtInboundPolicy=void 0;var gp=(Ts(),eo(vs)),bp=L(),UR=se(),yp={},kR=s(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new bp.ConfigurationError("Invalid State - jwkUrl not set");yp[t.jwkUrl]||(yp[t.jwkUrl]=(0,gp.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,gp.jwtVerify)(e,yp[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),MR=s(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let o=new TextEncoder().encode(t.secret);r=new Uint8Array(o)}else r=t.secret;let{payload:n}=await(0,gp.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),HR=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),o="bearer ",a=s(m=>UR.HttpProblems.unauthorized(e,t,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new bp.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new bp.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?kR:MR,l=await s(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(o)!==0)return a("Invalid bearer token format for authorization header");let m=i.substring(o.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(h){let y=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${y.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");_a.OpenIdJwtInboundPolicy=HR});var Xg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.Auth0JwtInboundPolicy=void 0;var FR=jt(),qR=s(async(e,t,r,n)=>(0,FR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Ea.Auth0JwtInboundPolicy=qR});var eb=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.BasicAuthInboundPolicy=void 0;var $R=se(),jR=s(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",o=s(l=>$R.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!n)return await o("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await o("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await o("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await o("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===h);return y||await o("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");wa.BasicAuthInboundPolicy=jR});var tb=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.CachingInboundPolicy=void 0;var VR=$t(),GR=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function BR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(BR,"digestMessage");var KR=s(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await BR(JSON.stringify(n)),o=new URL(e.url),a=new URLSearchParams(o.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${o.origin}${o.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function JR(e,t,r,n){let i=await(0,VR.getPolicyCacheName)(n,r),o=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await KR(e,r),u=await o.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let m=r?.expirationSecondsTtl??60,h=new Response(p.body,p);GR.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${m}`),t.waitUntil(o.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}s(JR,"CachingInboundPolicy");va.CachingInboundPolicy=JR});var rb=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ChangeMethodInboundPolicy=void 0;var zR=L(),WR=He(),QR=s(async(e,t,r,n)=>{if(!r.method)throw new zR.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new WR.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");Ta.ChangeMethodInboundPolicy=QR});var nb=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.ClearHeadersInboundPolicy=void 0;var YR=He(),ZR=s(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new YR.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");Sa.ClearHeadersInboundPolicy=ZR});var ib=g(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.ClearHeadersOutboundPolicy=void 0;var XR=s(async(e,t,r,n)=>{let i=[...n.exclude??[]],o=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&o.set(c,u)}),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");Ia.ClearHeadersOutboundPolicy=XR});var ob=g(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.ClerkJwtInboundPolicy=void 0;var e0=jt(),t0=s(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),o=new URL(i);return o.pathname="/.well-known/jwks.json",(0,e0.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:o.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");Pa.ClerkJwtInboundPolicy=t0});var ab=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.CognitoJwtInboundPolicy=void 0;var sb=L(),r0=jt(),n0=s(async(e,t,r,n)=>{if(!r.userPoolId)throw new sb.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new sb.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,r0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");Aa.CognitoJwtInboundPolicy=n0});var ub=g(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.CompositeInboundPolicy=void 0;var i0=L(),o0=mn(),cb=zr(),s0=s(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new i0.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=o0.Gateway.instance,o=(0,cb.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,cb.toStackedInboundHandler)(o)(e,t)},"CompositeInboundPolicy");Ra.CompositeInboundPolicy=s0});var db=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.CreditsMeteringInboundPolicy=void 0;var Ri=se(),lb=Y(),a0=s(async(e,t,r)=>{let n=e.user;if(!n)return Ri.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return Ri.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let o=r.bucketId,a=await c0(o,i,t);if(!a)return Ri.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return Ri.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return Ri.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await u0(o,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");Oa.CreditsMeteringInboundPolicy=a0;async function c0(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=lb.Environment.instance,o=new URL(`${i}/internal/v1/metering/${e}/subscriptions`);o.search=new URLSearchParams({customerKey:t,status:"active"}).toString();let a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}s(c0,"getSubscription");async function u0(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=lb.Environment.instance,a=new URL(`${o}/internal/v1/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}s(u0,"consumeSubscription")});var pb=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.CurityPhantomTokenInboundPolicy=void 0;var l0=$t(),d0=Jt(),Na=se(),p0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return Na.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let o=h0(i);if(!o)return Na.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,l0.getPolicyCacheName)(n,r),c=new d0.MemoryZoneReadThroughCache(a,t),u=await c.get(o);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+o+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(o,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),Na.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):Na.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");xa.CurityPhantomTokenInboundPolicy=p0;function h0(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}s(h0,"getToken")});var hb=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.FirebaseJwtInboundPolicy=void 0;var f0=qt(),m0=jt(),y0=s(async(e,t,r,n)=>((0,f0.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,m0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");Ca.FirebaseJwtInboundPolicy=y0});var fb=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.FormDataToJsonInboundPolicy=void 0;var g0=He(),b0=s(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",o=e.headers.get("content-type")?.toLowerCase();if(!o||![i,n].includes(o))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new g0.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");La.FormDataToJsonInboundPolicy=b0});var mb=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.GeoFilterInboundPolicy=void 0;var _0=L(),E0=se(),Ln="__unknown__",w0=s(async(e,t,r,n)=>{let i={allow:{countries:Un(r.allow?.countries,"allow.countries",n),regionCodes:Un(r.allow?.regionCodes,"allow.regionCode",n),asns:Un(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Un(r.block?.countries,"block.countries",n),regionCodes:Un(r.block?.regionCodes,"block.regionCode",n),asns:Un(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},o=t.incomingRequestProperties.country?.toLowerCase()??Ln,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Ln,c=t.incomingRequestProperties.asn?.toString()??Ln,u=i.ignoreUnknown&&o===Ln,l=i.ignoreUnknown&&a===Ln,d=i.ignoreUnknown&&c===Ln,p=i.allow.countries,m=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(o)&&!u||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Dn(e,t,n,o,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(o)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Dn(e,t,n,o,a,c):e},"GeoFilterInboundPolicy");Da.GeoFilterInboundPolicy=w0;function Dn(e,t,r,n,i,o){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${o}')`),E0.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:o}})}s(Dn,"blockedResponse");function Un(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new _0.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}s(Un,"toLowerStringArray")});var yb=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.JWTScopeValidationInboundPolicy=void 0;var v0=s(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!s((o,a)=>a.every(c=>o.includes(c)),"scopeChecker")(n,r.scopes)){let o={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(o),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");Ua.JWTScopeValidationInboundPolicy=v0});var bb=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.MockApiInboundPolicy=void 0;var T0=se(),S0=s(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return _p(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let o=Object.keys(i),a=[];if(o.length===0)return _p(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(o.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return gb(a[c])}else return a.length>0?gb(a[0]):_p(n,e,t,"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");ka.MockApiInboundPolicy=S0;function gb(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}s(gb,"generateResponse");var _p=s((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return T0.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Tb=g(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.MoesifInboundPolicy=kn.setMoesifContext=void 0;var I0=L(),P0=ve(),A0="Incoming",R0={logRequestBody:!0,logResponseBody:!0};function _b(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}s(_b,"headersToObject");function Eb(){return new Date().toISOString()}s(Eb,"timestamp");var Ep=new WeakMap,O0={};function N0(e,t){let r=Ep.get(e);r||(r=O0);let n=Object.assign({...r},t);Ep.set(e,n)}s(N0,"setMoesifContext");kn.setMoesifContext=N0;async function wb(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}s(wb,"readBody");var x0={},wp;function vb(){if(!wp)throw new I0.RuntimeError("Invalid State - no _lastLogger");return wp}s(vb,"getLastLogger");function C0(e){let t=x0[e];return t||(t=new P0.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);vb().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||vb().error({status:i.status,body:await i.text()})})),t}s(C0,"getDispatcher");async function L0(e,t,r,n){wp=t.log;let i=Eb(),o=Object.assign(R0,r);if(!o.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=o.logRequestBody?await wb(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=C0(o.applicationId),d=e.headers.get("true-client-ip"),p=Ep.get(t)??{},m={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:_b(e.headers)},h=o.logResponseBody?await wb(c,t):void 0,y={time:Eb(),status:c.status,headers:_b(c.headers),body:h},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:A0};l.enqueue(v),t.waitUntil(l.waitUntilFlushed())}),e}s(L0,"MoesifInboundPolicy");kn.MoesifInboundPolicy=L0});var Sb=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.OktaJwtInboundPolicy=void 0;var D0=jt(),U0=s(async(e,t,r,n)=>(0,D0.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Ma.OktaJwtInboundPolicy=U0});var Ib=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.PropelAuthJwtInboundPolicy=void 0;var k0=(Ts(),eo(vs)),M0=jt(),vp,H0=s(async(e,t,r,n)=>{if(!vp)try{vp=await(0,k0.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,M0.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:vp,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ha.PropelAuthJwtInboundPolicy=H0});var Pb=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var je=Dt(),et=class extends Error{static{s(this,"ValidationError")}constructor(t){super(t)}};G.ValidationError=et;var Oi=class extends et{static{s(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};G.ArgumentUndefinedError=Oi;var Ni=class extends et{static{s(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ni;function F0(e,t){if((0,je.isUndefined)(e))throw new Oi(t)}s(F0,"throwIfUndefined");G.throwIfUndefined=F0;function Tp(e,t){if((0,je.isUndefinedOrNull)(e))throw new Oi(t)}s(Tp,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Tp;function q0(e,t){if(Tp(e,t),!(0,je.isString)(e))throw new Ni(t,"string")}s(q0,"throwIfNotString");G.throwIfNotString=q0;function $0(e,t){if(Tp(e,t),!(0,je.isNumber)(e))throw new Ni(t,"number")}s($0,"throwIfNotNumber");G.throwIfNotNumber=$0;var xi=class extends et{static{s(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};G.OptionUndefinedError=xi;var Mn=class extends et{static{s(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=Mn;function j0(e,t,r,n){if((0,je.isUndefined)(n))throw new xi(e,t,r)}s(j0,"throwIfOptionUndefined");G.throwIfOptionUndefined=j0;function Fa(e,t,r,n){if((0,je.isUndefinedOrNull)(n))throw new xi(e,t,r)}s(Fa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Fa;function V0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isString)(n))throw new Mn(e,t,r,"string")}s(V0,"throwIfOptionNotString");G.throwIfOptionNotString=V0;function G0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isNumber)(n))throw new Mn(e,t,r,"number")}s(G0,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=G0;function B0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isObject)(n))throw new Mn(e,t,r,"object")}s(B0,"throwIfOptionNotObject");G.throwIfOptionNotObject=B0;function K0(e,t){if((0,je.isUndefined)(e))throw new et(t)}s(K0,"throwIfStateUndefined");G.throwIfStateUndefined=K0;function qa(e,t){if((0,je.isUndefinedOrNull)(e))throw new et(t)}s(qa,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=qa;function J0(e,t){if(qa(e,t),!(0,je.isString)(e))throw new et(t);return!0}s(J0,"throwIfStateNotString");G.throwIfStateNotString=J0;function z0(e,t){if(qa(e,t),!(0,je.isNumber)(e))throw new et(t);return!0}s(z0,"throwIfStateNotNumber");G.throwIfStateNotNumber=z0;function W0(e,t){if(qa(e,t),!(0,je.isObject)(e))throw new et(t);return!0}s(W0,"throwIfStateNotObject");G.throwIfStateNotObject=W0});var Ab=g(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.InMemoryRedisClient=Hn.StandardRedisClient=void 0;var Sp=L(),$a=Pb(),Ip=class e{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,$a.throwIfNotString)(t,"redisClientUrl"),(0,$a.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,$a.throwIfNotString)(t,"url");let o=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=o.headers.get("Content-Type")?.includes("application/json")?await o.json():await o.text();if(o.ok)return a;throw o.status===401?new Sp.SystemError("Redis client failed with 401: Unauthorized"):new Sp.SystemError(`Redis client failed with (${o.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Hn.StandardRedisClient=Ip;var Pp=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,$a.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:o,key:a}=JSON.parse(r),c=Date.now()+o*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Sp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Hn.InMemoryRedisClient=Pp});var Cb=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.RateLimitInboundPolicy=void 0;var Q0=Sr(),Y0=$t(),Z0=oo(),Vt=L(),X0=se(),Rb=Le(),Ci=Y(),Ob=Ab(),Nb=Dt(),ja=(0,Q0.debug)("zuplo:policies:RateLimitInboundPolicy"),eO="strict",tO=s(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),rO=s(async e=>({key:`ip-${tO(e)}`}),"getIP"),nO=s(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),iO=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Va;function oO(e,t){let r;if(Va)return Va;if(Ci.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Ob.InMemoryRedisClient,Va=r,r;let{authApiJWT:n,redisURL:i}=Ci.Environment.instance;if(!(0,Nb.isString)(i))throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,Nb.isString)(n))throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Ob.StandardRedisClient.initialize(i,n,Ci.Environment.instance.deploymentName??"unknown",Ci.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Va=r,r}s(oO,"getRedisClient");async function xb(e,t,r,n,i){let o=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:i})}s(xb,"getCountAndUpdateExpiry");function sO(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,o,a)=>{let c=await r(i,o,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw o.log.error(u),new Vt.RuntimeError(u)}return c},"outerFunction")}s(sO,"wrapUserFunction");var aO="Retry-After",cO=s(async(e,t,r,n)=>{let i=Date.now(),o=Rb.SystemLogMap.getLogger(t),a=s((u,l)=>{if(r.throwOnFailure)throw new Vt.SystemError(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[aO]=l.toString()),X0.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:sO(r,n),user:nO,ip:rO,all:iO}[r.rateLimitBy],d=await l(e,t,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=oO(n,o),S=`bucket/${Ci.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??eO)==="async"){let C=await(0,Y0.getPolicyCacheName)(n,r),re=new Z0.ZoneCache(C,{logger:Rb.SystemLogMap.getLogger(t)}),ne=xb(S,h,v,o,t.requestId),me=await re.get(S);if(me!==void 0&&me<=Date.now()){ja(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Be=Math.round((me-Date.now())/1e3);return c(y,Be)}return t.addEventListener("responseSending",Be=>{try{let E=Be,H=E.mutableResponse;E.mutableResponse=(async()=>{let Ce=await ne;if(Ce.count>m){let ou=Date.now()+Ce.ttlSeconds*1e3;return re.put(S,ou,Ce.ttlSeconds).catch(fh=>{throw o.error(fh),fh}),ja(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(y,Ce.ttlSeconds)}return H})()}catch(E){o.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let j=await xb(S,h,v,o,t.requestId);return j.count>m?(ja(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(y,j.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;ja(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Ga.RateLimitInboundPolicy=cO});var kb=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.ReadmeMetricsInboundPolicy=void 0;var uO=ve(),Ap=Y(),Lb=ii(),Rp;function Db(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}s(Db,"headersToNameValuePairs");function lO(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}s(lO,"queryToNameValueParis");function dO(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}s(dO,"parseIntOrUndefined");var Ub={};async function pO(e,t,r,n){let i=new Date,o=Date.now();return Rp||(Rp={name:"zuplo",version:Ap.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Ap.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,Lb.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,Lb.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Ap.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:Rp,entries:[{startedDateTime:i.toISOString(),time:Date.now()-o,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:Db(e.headers),queryString:lO(e.query)},response:{status:a.status,statusText:a.statusText,headers:Db(a.headers),content:{size:dO(e.headers.get("content-length"))}}}]}}},d=Ub[r.apiKey];if(!d){let p=r.apiKey;d=new uO.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),Ub[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}s(pO,"ReadmeMetricsInboundPolicy");Ba.ReadmeMetricsInboundPolicy=pO});var Mb=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.RemoveHeadersInboundPolicy=void 0;var hO=L(),fO=He(),mO=s(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new hO.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let o=new Headers(e.headers);return i.forEach(c=>{o.delete(c)}),new fO.ZuploRequest(e,{headers:o})},"RemoveHeadersInboundPolicy");Ka.RemoveHeadersInboundPolicy=mO});var Hb=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.RemoveHeadersOutboundPolicy=void 0;var yO=L(),gO=s(async(e,t,r,n,i)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new yO.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return o.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Ja.RemoveHeadersOutboundPolicy=gO});var Fb=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.RemoveQueryParamsInboundPolicy=void 0;var bO=L(),_O=He(),EO=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new bO.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let o=new URL(e.url);return i.forEach(c=>{o.searchParams.delete(c)}),new _O.ZuploRequest(o.toString(),e)},"RemoveQueryParamsInboundPolicy");za.RemoveQueryParamsInboundPolicy=EO});var qb=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ReplaceStringOutboundPolicy=void 0;var wO=s(async(e,t,r,n)=>{let i=await e.text(),o=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(o,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Wa.ReplaceStringOutboundPolicy=wO});var jb=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.RequestSizeLimitInboundPolicy=void 0;var $b=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),vO=s(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),o=i!==null?parseInt(i):void 0;return o&&!isNaN(o)&&o>r.maxSizeInBytes?$b():o&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?$b():e},"RequestSizeLimitInboundPolicy");Qa.RequestSizeLimitInboundPolicy=vO});var Ya=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function TO(e,t,r){return`_${Mr(e+"_"+t+"_"+r)}`}s(TO,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=TO;function SO(e,t,r,n){return`_${Mr(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}s(SO,"getIdForParameterSchema");tt.getIdForParameterSchema=SO;function IO(e,t,r){return`_${Mr(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Mr(r.toLowerCase())}`}s(IO,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=IO;function PO(e,t){return`_${Mr(e)}__${Mr(t)}`}s(PO,"getIdForRefSchema");tt.getIdForRefSchema=PO;function Mr(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}s(Mr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Mr});var Li=g(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.getErrorsFromValidator=De.shouldReject=De.shouldLog=De.logErrors=De.validateParameters=De.getParametersForOperation=void 0;var AO=mn(),RO=Ya(),OO=s(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");De.getParametersForOperation=OO;var NO=s((e,t,r,n,i)=>{let o=[],a=!0,c=[];return e.forEach(u=>{if(u.required&&!t[u.name])a=!1,o.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,RO.getIdForParameterSchema)(r,n,i,u.name),d=AO.Gateway.instance.schemaValidator[l],p=d(t[u.name]),m=(0,De.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),o.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:o}},"validateParameters");De.validateParameters=NO;var xO=s((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");De.logErrors=xO;var CO=s(e=>e==="log-only"||e==="reject-and-log","shouldLog");De.shouldLog=CO;var LO=s(e=>e==="reject-only"||e==="reject-and-log","shouldReject");De.shouldReject=LO;var DO=s(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");De.getErrorsFromValidator=DO});var Vb=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.handleBodyValidation=void 0;var UO=mn(),Za=se(),kO=Ya(),Je=Li();async function MO(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let y=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,v=Za.HttpProblems.badRequest(t,e,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",y,[n],h),(0,Je.shouldReject)(r.validateBody))return v}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,y=Za.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?y:void 0}let i=t.headers.get("Content-Type"),o=i.indexOf(";");o>-1&&(i=i.substring(0,o));let a=(0,kO.getIdForRequestBodySchema)(e.route.path,t.method,i),c=UO.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,y=Za.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),m=Za.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return m}s(MO,"handleBodyValidation");Xa.handleBodyValidation=MO});var Gb=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.handleHeadersValidation=void 0;var HO=se(),Di=Li();function FO(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,Di.getParametersForOperation)(e),o=(0,Di.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!o.isValid){let a="Header validation failed",c=HO.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:o.errors});if((0,Di.shouldLog)(r.validateHeaders)&&(0,Di.logErrors)(e,r.logLevel??"info",a,o.invalidValues,o.errors),(0,Di.shouldReject)(r.validateHeaders))return c}}s(FO,"handleHeadersValidation");ec.handleHeadersValidation=FO});var Bb=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.handlePathParameterValidation=void 0;var qO=se(),Ui=Li();function $O(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Ui.getParametersForOperation)(e),i=(0,Ui.validateParameters)(n.filter(o=>o.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let o="Path parameters validation failed",a=qO.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Ui.shouldLog)(r.validatePathParameters)&&(0,Ui.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Ui.shouldReject)(r.validatePathParameters))return a}}s($O,"handlePathParameterValidation");tc.handlePathParameterValidation=$O});var Kb=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.handleQueryParameterValidation=void 0;var jO=se(),ki=Li();function VO(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,ki.getParametersForOperation)(e),i=(0,ki.validateParameters)(n.filter(o=>o.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let o="Query parameters validation failed",a=jO.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,ki.shouldLog)(r.validateQueryParameters)&&(0,ki.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,ki.shouldReject)(r.validateQueryParameters))return a}}s(VO,"handleQueryParameterValidation");rc.handleQueryParameterValidation=VO});var Jb=g(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.SchemaBasedRequestValidation=Hr.RequestValidationInboundPolicy=void 0;var GO=Vb(),BO=Gb(),KO=Bb(),JO=Kb(),zO=s(async(e,t,r)=>{let n=(0,JO.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,KO.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,BO.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,GO.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Hr.RequestValidationInboundPolicy=zO;Hr.SchemaBasedRequestValidation=Hr.RequestValidationInboundPolicy});var zb=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.RequireOriginInboundPolicy=void 0;var WO=L(),QO=se(),YO=s(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new WO.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let o=e.headers.get("origin");if(!o||!i.includes(o)){let a=r.failureDetail??"Forbidden";return QO.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");nc.RequireOriginInboundPolicy=YO});var Wb=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.SetBodyInboundPolicy=void 0;var ZO=He(),XO=s(async(e,t,r)=>new ZO.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");ic.SetBodyInboundPolicy=XO});var Yb=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.SetHeadersInboundPolicy=void 0;var Qb=L(),eN=He(),tN=s(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new Qb.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let o=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Qb.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.has(c.name)||u)&&o.set(c.name,c.value)}),new eN.ZuploRequest(e,{headers:o})},"SetHeadersInboundPolicy");oc.SetHeadersInboundPolicy=tN});var Xb=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.SetHeadersOutboundPolicy=void 0;var Zb=L(),rN=s(async(e,t,r,n,i)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new Zb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new Zb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");sc.SetHeadersOutboundPolicy=rN});var t_=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.SetQueryParamsInboundPolicy=void 0;var e_=L(),nN=He(),iN=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new e_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let o=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new e_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.searchParams.has(c.name)||u)&&o.searchParams.set(c.name,c.value)}),new nN.ZuploRequest(o.toString(),e)},"SetQueryParamsInboundPolicy");ac.SetQueryParamsInboundPolicy=iN});var r_=g(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.SetStatusOutboundPolicy=void 0;var oN=s(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");cc.SetStatusOutboundPolicy=oN});var n_=g(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.SleepInboundPolicy=void 0;var sN=L(),aN=s(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),cN=s(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new sN.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await aN(r.sleepInMs),e},"SleepInboundPolicy");uc.SleepInboundPolicy=cN});var o_=g(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.SupabaseJwtInboundPolicy=void 0;var i_=L(),uN=se(),lN=He(),dN=qt(),pN=jt(),hN=s(async(e,t,r,n)=>{(0,dN.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},o=await(0,pN.OpenIdJwtInboundPolicy)(e,t,i,n);if(o instanceof Response)return o;if(!(o instanceof lN.ZuploRequest))throw new i_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return o;let c=e.user?.data.app_metadata;if(!c)throw new i_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?uN.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):o},"SupabaseJwtInboundPolicy");lc.SupabaseJwtInboundPolicy=hN});var a_=g(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var fN=$t(),mN=Jt(),s_=L(),yN=Le(),gN=Is(),bN=qt(),_N=s(async(e,t,r,n)=>{(0,bN.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,fN.getPolicyCacheName)(n,r),o=new mN.MemoryZoneReadThroughCache(i,{logger:yN.SystemLogMap.getLogger(t)}),a=await o.get(n);if(!a){let c=await EN(r,t);o.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");dc.UpstreamAzureAdServiceAuthInboundPolicy=_N;async function EN(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,gN.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let o=await n.text();t.log.error("Could not get token from Azure AD",o)}catch{}throw new s_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new s_.RuntimeError("Response returned from Azure AD is not in the expected format.")}s(EN,"getAccessToken")});var u_=g(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var wN=$t(),vN=Jt(),TN=L(),SN=Le(),Op=pn(),IN=qt(),c_="https://accounts.google.com/o/oauth2/token",Np,PN=s(async(e,t,r,n)=>{(0,IN.optionValidator)(r,n).required("serviceAccountJson","string"),Np||(Np=await Op.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},o=await(0,wN.getPolicyCacheName)(n,r),a=new vN.MemoryZoneReadThroughCache(o,{logger:SN.SystemLogMap.getLogger(t)}),c=await a.get(n);if(!c){let u=await(0,Op.getTokenFromGcpServiceAccount)({serviceAccount:Np,audience:c_,payload:i}),l=await(0,Op.exchangeGgpJwtForIdToken)(c_,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new TN.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");pc.UpstreamFirebaseAdminAuthInboundPolicy=PN});var l_=g(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var AN=$t(),RN=Jt(),Fn=L(),ON=Le(),NN=dp(),xp=pn(),xN=ii(),CN=qt(),LN="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",DN=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Cp,UN=s(async(e,t,r,n)=>{if((0,CN.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Fn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(DN.indexOf(p)!==-1)throw new Fn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Cp||(Cp=await xp.GcpServiceAccount.init(r.serviceAccountJson));let o=r.userId;if(!o&&!r.userIdPropertyPath){if(!e.user)throw new Fn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");o=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new Fn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);o=(0,xN.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!o)throw new Fn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,AN.getPolicyCacheName)(n,r),c=new RN.MemoryZoneReadThroughCache(a,{logger:ON.SystemLogMap.getLogger(t)}),u={uid:o,claims:i},l=await(0,NN.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,xp.getTokenFromGcpServiceAccount)({serviceAccount:Cp,audience:LN,payload:u}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,xp.exchangeFirebaseJwtForIdToken)(m,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new Fn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");hc.UpstreamFirebaseUserAuthInboundPolicy=UN});var p_=g(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.UpstreamGcpJwtInboundPolicy=void 0;var d_=pn(),kN=qt(),Lp,MN=s(async(e,t,r,n)=>{(0,kN.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Lp||(Lp=await d_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,d_.getTokenFromGcpServiceAccount)({serviceAccount:Lp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");fc.UpstreamGcpJwtInboundPolicy=MN});var f_=g(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.UpstreamGcpServiceAuthInboundPolicy=void 0;var HN=$t(),FN=pu(),qN=Jt(),$N=L(),Dp=pn(),jN=qt(),h_="https://www.googleapis.com/oauth2/v4/token",Up,VN=s(async(e,t,r,n)=>{(0,jN.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Up||(Up=await Dp.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,HN.getPolicyCacheName)(n,r),o;r.useMemoryCacheOnly?o=new FN.MemoryCache(i):o=new qN.MemoryZoneReadThroughCache(i,t);let a=await o.get(n);if(!a){let c=await(0,Dp.getTokenFromGcpServiceAccount)({serviceAccount:Up,audience:h_,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,Dp.exchangeGgpJwtForIdToken)(h_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new $N.RuntimeError("Invalid token response from GCP");a=u,o.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");mc.UpstreamGcpServiceAuthInboundPolicy=VN});var y_=g(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.ValidateJsonSchemaInbound=void 0;var GN=L(),m_=se(),BN=s(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return m_.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new GN.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return m_.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");yc.ValidateJsonSchemaInbound=BN});var __=g(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.MeteringInboundPolicy=void 0;var g_=Vs(),b_=yn(),gc=L(),KN=se(),JN=Le(),zN=Y(),WN=s(async(e,t,r,n)=>{let i=JN.SystemLogMap.getLogger(t);t.addResponseSendingFinalHook(async(d,p,m)=>{let h=g_.ContextData.get(m,"subscription");if((r.allowRequestsWithoutSubscription??!1)&&!h)return;if(!r.bucketId)if(b_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=b_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new gc.ConfigurationError(`MeteringInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:v,meteringServiceUrl:T}=zN.Environment.instance;d.ok&&h&&r.meters&&fetch(`${T}/internal/v1/metering/${r.bucketId}/subscriptions/${h.id}/quotas/consume`,{headers:{Authorization:`Bearer ${v}`},method:"POST",body:JSON.stringify({meters:r.meters})}).catch(S=>{m.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`,S)})});let o=g_.ContextData.get(t,"subscription"),a=r.allowRequestsWithoutSubscription??!1,c=r.allowRequestsOverQuota??!1;if(!o){if(a)return e;throw new gc.ConfigurationError("Subscription is not available for user")}if(o&&Object.keys(o.quotas).length===0)throw new gc.ConfigurationError("Quota is not set up for the user's subscription");let l=Object.keys(r.meters).filter(d=>!Object.keys(o.quotas).includes(d));if(l.length>0)throw new gc.ConfigurationError(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(o.quotas))if(o.quotas[d]<=0&&!c)return KN.HttpProblems.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return e},"MeteringInboundPolicy");bc.MeteringInboundPolicy=WN});var w_=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.LoadSubscriptionInboundPolicy=void 0;var QN=Vs(),E_=yn(),YN=L(),kp=se(),ZN=Le(),XN=Y(),ex=s(async(e,t,r,n)=>{let i=ZN.SystemLogMap.getLogger(t),o=r.allowRequestsWithoutSubscription??!1,a=e.user;if(!a)return o?e:kp.HttpProblems.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!r.bucketId)if(E_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=E_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new YN.ConfigurationError(`LoadSubscriptionInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:c,meteringServiceUrl:u}=XN.Environment.instance,{sub:l}=a,d,p;try{if(d=await fetch(`${u}/internal/v1/metering/${r.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${c}`},method:"GET"}),!d.ok)return t.log.error(await d.text()),kp.HttpProblems.forbidden(e,t);p=await d.json()}catch(h){i.error(`LoadSubscriptionInboundPolicy '${n}' -error in serviceResponse`,h)}if((!p||!p.data||p.data.length===0)&&!o)return kp.HttpProblems.unauthorized(e,t,{detail:"No valid, active subscription found"});if((!p||!p.data||p.data.length===0)&&o)return e;let m=p&&p.data?p.data[0]:void 0;return QN.ContextData.set(t,"subscription",m),e},"LoadSubscriptionInboundPolicy");_c.LoadSubscriptionInboundPolicy=ex});var v_=g(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.ServiceProviderImpl=void 0;var tx=L(),Mp=class e{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return e.#e||(e.#e=new e),e.#e}setInstance(t){e.#e=t}addService(t,r){if(this.services.get(t))throw new tx.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Ec.ServiceProviderImpl=Mp});var L_=g(f=>{"use strict";var rx=f&&f.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Hp=f&&f.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&rx(t,e,r)},nx=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});f.RateLimitInboundPolicy=f.BasicRateLimitInboundPolicy=f.PropelAuthJwtInboundPolicy=f.OpenIdJwtInboundPolicy=f.OktaJwtInboundPolicy=f.setMoesifContext=f.MoesifInboundPolicy=f.MockApiInboundPolicy=f.JWTScopeValidationInboundPolicy=f.GeoFilterInboundPolicy=f.FormDataToJsonInboundPolicy=f.FirebaseJwtInboundPolicy=f.CurityPhantomTokenInboundPolicy=f.CreditsMeteringInboundPolicy=f.CompositeInboundPolicy=f.CognitoJwtInboundPolicy=f.ClerkJwtInboundPolicy=f.ClearHeadersOutboundPolicy=f.ClearHeadersInboundPolicy=f.ChangeMethodInboundPolicy=f.CachingInboundPolicy=f.BasicAuthInboundPolicy=f.Auth0JwtInboundPolicy=f.ApiKeyInboundPolicy=f.ApiAuthKeyInboundPolicy=f.AmberfloMeteringPolicy=f.AmberfloMeteringInboundPolicy=f.AuditLogPlugin=f.AuditLogDataStaxProvider=f.HttpStatusCode=f.webSocketPipelineHandler=f.webSocketHandler=f.urlRewriteHandler=f.urlForwardHandler=f.redirectHandler=f.openApiSpecHandler=f.awsLambdaHandler=f.AwsLambdaHandlerExtensions=f.purgeGatewayCache=f.Handler=f.originalFetch=f.ConfigurationError=f.isZuploReadableEnvVariableName=f.isRestrictedEnvVariableName=f.environment=f.ContextData=f.ResponseSentEvent=f.ResponseSendingEvent=f.ZoneCache=f.MemoryZoneReadThroughCache=void 0;f.sanitizedIdentifierName=f.getRawOperationDataIdentifierName=f.getIdForRequestBodySchema=f.getIdForRefSchema=f.getIdForParameterSchema=f.SystemLogMap=f.httpStatuses=f.SYSTEM_LOGGER=f.API_KEY=f.ServiceProviderImpl=f.serialize=f.ContentTypes=f.Router=f.LookupResult=f.SystemRouteName=f.ZuploRequest=f.ProblemResponseFormatter=f.HttpProblems=f.LoadSubscriptionInboundPolicy=f.MeteringInboundPolicy=f.ValidateJsonSchemaInbound=f.UpstreamGcpServiceAuthInboundPolicy=f.UpstreamGcpJwtInboundPolicy=f.UpstreamFirebaseUserAuthInboundPolicy=f.UpstreamFirebaseAdminAuthInboundPolicy=f.UpstreamAzureAdServiceAuthInboundPolicy=f.SupabaseJwtInboundPolicy=f.StripeWebhookVerificationInboundPolicy=f.SleepInboundPolicy=f.SetStatusOutboundPolicy=f.SetQueryParamsInboundPolicy=f.SetHeadersOutboundPolicy=f.SetHeadersInboundPolicy=f.SetBodyInboundPolicy=f.RequireOriginInboundPolicy=f.SchemaBasedRequestValidation=f.RequestValidationInboundPolicy=f.RequestSizeLimitInboundPolicy=f.ReplaceStringOutboundPolicy=f.RemoveQueryParamsInboundPolicy=f.RemoveHeadersOutboundPolicy=f.RemoveHeadersInboundPolicy=f.ReadmeMetricsInboundPolicy=void 0;Eh();var ix=Jt();Object.defineProperty(f,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return ix.MemoryZoneReadThroughCache}});var ox=oo();Object.defineProperty(f,"ZoneCache",{enumerable:!0,get:function(){return ox.ZoneCache}});var T_=Ir();Object.defineProperty(f,"ResponseSendingEvent",{enumerable:!0,get:function(){return T_.ResponseSendingEvent}});Object.defineProperty(f,"ResponseSentEvent",{enumerable:!0,get:function(){return T_.ResponseSentEvent}});var sx=Vs();Object.defineProperty(f,"ContextData",{enumerable:!0,get:function(){return sx.ContextData}});var Fp=yn();Object.defineProperty(f,"environment",{enumerable:!0,get:function(){return Fp.environment}});Object.defineProperty(f,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return Fp.isRestrictedEnvVariableName}});Object.defineProperty(f,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return Fp.isZuploReadableEnvVariableName}});var ax=L();Object.defineProperty(f,"ConfigurationError",{enumerable:!0,get:function(){return ax.ConfigurationError}});var cx=Sd();Object.defineProperty(f,"originalFetch",{enumerable:!0,get:function(){return cx.originalFetch}});var S_=zy();Object.defineProperty(f,"Handler",{enumerable:!0,get:function(){return S_.Handler}});Object.defineProperty(f,"purgeGatewayCache",{enumerable:!0,get:function(){return S_.purgeGatewayCache}});var I_=dg();Object.defineProperty(f,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return I_.AwsLambdaHandlerExtensions}});Object.defineProperty(f,"awsLambdaHandler",{enumerable:!0,get:function(){return I_.awsLambdaHandler}});var ux=hg();Object.defineProperty(f,"openApiSpecHandler",{enumerable:!0,get:function(){return ux.openApiSpecHandler}});var lx=fg();Object.defineProperty(f,"redirectHandler",{enumerable:!0,get:function(){return lx.redirectHandler}});var dx=yg();Object.defineProperty(f,"urlForwardHandler",{enumerable:!0,get:function(){return dx.urlForwardHandler}});var px=bg();Object.defineProperty(f,"urlRewriteHandler",{enumerable:!0,get:function(){return px.urlRewriteHandler}});var hx=Eg();Object.defineProperty(f,"webSocketHandler",{enumerable:!0,get:function(){return hx.webSocketHandler}});var fx=Tg();Object.defineProperty(f,"webSocketPipelineHandler",{enumerable:!0,get:function(){return fx.webSocketPipelineHandler}});var mx=ku();Object.defineProperty(f,"HttpStatusCode",{enumerable:!0,get:function(){return mx.HttpStatusCode}});Hp(xg(),f);Hp(Dg(),f);var yx=Ug();Object.defineProperty(f,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return yx.AuditLogDataStaxProvider}});var gx=Mg();Object.defineProperty(f,"AuditLogPlugin",{enumerable:!0,get:function(){return gx.AuditLogPlugin}});Hp(Vg(),f);var P_=zg();Object.defineProperty(f,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return P_.AmberfloMeteringInboundPolicy}});Object.defineProperty(f,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return P_.AmberfloMeteringPolicy}});var bx=Zg();Object.defineProperty(f,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return bx.ApiAuthKeyInboundPolicy}});var _x=mp();Object.defineProperty(f,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return _x.ApiKeyInboundPolicy}});var Ex=Xg();Object.defineProperty(f,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return Ex.Auth0JwtInboundPolicy}});var wx=eb();Object.defineProperty(f,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return wx.BasicAuthInboundPolicy}});var vx=tb();Object.defineProperty(f,"CachingInboundPolicy",{enumerable:!0,get:function(){return vx.CachingInboundPolicy}});var Tx=rb();Object.defineProperty(f,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return Tx.ChangeMethodInboundPolicy}});var Sx=nb();Object.defineProperty(f,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return Sx.ClearHeadersInboundPolicy}});var Ix=ib();Object.defineProperty(f,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return Ix.ClearHeadersOutboundPolicy}});var Px=ob();Object.defineProperty(f,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return Px.ClerkJwtInboundPolicy}});var Ax=ab();Object.defineProperty(f,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return Ax.CognitoJwtInboundPolicy}});var Rx=ub();Object.defineProperty(f,"CompositeInboundPolicy",{enumerable:!0,get:function(){return Rx.CompositeInboundPolicy}});var Ox=db();Object.defineProperty(f,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return Ox.CreditsMeteringInboundPolicy}});var Nx=pb();Object.defineProperty(f,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return Nx.CurityPhantomTokenInboundPolicy}});var xx=hb();Object.defineProperty(f,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return xx.FirebaseJwtInboundPolicy}});var Cx=fb();Object.defineProperty(f,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return Cx.FormDataToJsonInboundPolicy}});var Lx=mb();Object.defineProperty(f,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return Lx.GeoFilterInboundPolicy}});var Dx=yb();Object.defineProperty(f,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return Dx.JWTScopeValidationInboundPolicy}});var Ux=bb();Object.defineProperty(f,"MockApiInboundPolicy",{enumerable:!0,get:function(){return Ux.MockApiInboundPolicy}});var A_=Tb();Object.defineProperty(f,"MoesifInboundPolicy",{enumerable:!0,get:function(){return A_.MoesifInboundPolicy}});Object.defineProperty(f,"setMoesifContext",{enumerable:!0,get:function(){return A_.setMoesifContext}});var kx=Sb();Object.defineProperty(f,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return kx.OktaJwtInboundPolicy}});var Mx=jt();Object.defineProperty(f,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return Mx.OpenIdJwtInboundPolicy}});var Hx=Ib();Object.defineProperty(f,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return Hx.PropelAuthJwtInboundPolicy}});var R_=Cb();Object.defineProperty(f,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return R_.RateLimitInboundPolicy}});Object.defineProperty(f,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return R_.RateLimitInboundPolicy}});var Fx=kb();Object.defineProperty(f,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return Fx.ReadmeMetricsInboundPolicy}});var qx=Mb();Object.defineProperty(f,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return qx.RemoveHeadersInboundPolicy}});var $x=Hb();Object.defineProperty(f,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return $x.RemoveHeadersOutboundPolicy}});var jx=Fb();Object.defineProperty(f,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return jx.RemoveQueryParamsInboundPolicy}});var Vx=qb();Object.defineProperty(f,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return Vx.ReplaceStringOutboundPolicy}});var Gx=jb();Object.defineProperty(f,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return Gx.RequestSizeLimitInboundPolicy}});var O_=Jb();Object.defineProperty(f,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return O_.RequestValidationInboundPolicy}});Object.defineProperty(f,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return O_.SchemaBasedRequestValidation}});var Bx=zb();Object.defineProperty(f,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return Bx.RequireOriginInboundPolicy}});var Kx=Wb();Object.defineProperty(f,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return Kx.SetBodyInboundPolicy}});var Jx=Yb();Object.defineProperty(f,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return Jx.SetHeadersInboundPolicy}});var zx=Xb();Object.defineProperty(f,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return zx.SetHeadersOutboundPolicy}});var Wx=t_();Object.defineProperty(f,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Wx.SetQueryParamsInboundPolicy}});var Qx=r_();Object.defineProperty(f,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return Qx.SetStatusOutboundPolicy}});var Yx=n_();Object.defineProperty(f,"SleepInboundPolicy",{enumerable:!0,get:function(){return Yx.SleepInboundPolicy}});var Zx=op();Object.defineProperty(f,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return Zx.StripeWebhookVerificationInboundPolicy}});var Xx=o_();Object.defineProperty(f,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return Xx.SupabaseJwtInboundPolicy}});var eC=a_();Object.defineProperty(f,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return eC.UpstreamAzureAdServiceAuthInboundPolicy}});var tC=u_();Object.defineProperty(f,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return tC.UpstreamFirebaseAdminAuthInboundPolicy}});var rC=l_();Object.defineProperty(f,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return rC.UpstreamFirebaseUserAuthInboundPolicy}});var nC=p_();Object.defineProperty(f,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return nC.UpstreamGcpJwtInboundPolicy}});var iC=f_();Object.defineProperty(f,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return iC.UpstreamGcpServiceAuthInboundPolicy}});var oC=y_();Object.defineProperty(f,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return oC.ValidateJsonSchemaInbound}});var sC=__();Object.defineProperty(f,"MeteringInboundPolicy",{enumerable:!0,get:function(){return sC.MeteringInboundPolicy}});var aC=w_();Object.defineProperty(f,"LoadSubscriptionInboundPolicy",{enumerable:!0,get:function(){return aC.LoadSubscriptionInboundPolicy}});var cC=se();Object.defineProperty(f,"HttpProblems",{enumerable:!0,get:function(){return cC.HttpProblems}});var uC=mo();Object.defineProperty(f,"ProblemResponseFormatter",{enumerable:!0,get:function(){return uC.ProblemResponseFormatter}});var lC=He();Object.defineProperty(f,"ZuploRequest",{enumerable:!0,get:function(){return lC.ZuploRequest}});var dC=Ar();Object.defineProperty(f,"SystemRouteName",{enumerable:!0,get:function(){return dC.SystemRouteName}});var N_=md();Object.defineProperty(f,"LookupResult",{enumerable:!0,get:function(){return N_.LookupResult}});Object.defineProperty(f,"Router",{enumerable:!0,get:function(){return N_.Router}});var x_=Au();Object.defineProperty(f,"ContentTypes",{enumerable:!0,get:function(){return x_.ContentTypes}});Object.defineProperty(f,"serialize",{enumerable:!0,get:function(){return x_.serialize}});var pC=v_();Object.defineProperty(f,"ServiceProviderImpl",{enumerable:!0,get:function(){return pC.ServiceProviderImpl}});var C_=Wu();Object.defineProperty(f,"API_KEY",{enumerable:!0,get:function(){return C_.API_KEY}});Object.defineProperty(f,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return C_.SYSTEM_LOGGER}});var hC=Hu();Object.defineProperty(f,"httpStatuses",{enumerable:!0,get:function(){return nx(hC).default}});var fC=Le();Object.defineProperty(f,"SystemLogMap",{enumerable:!0,get:function(){return fC.SystemLogMap}});var Mi=Ya();Object.defineProperty(f,"getIdForParameterSchema",{enumerable:!0,get:function(){return Mi.getIdForParameterSchema}});Object.defineProperty(f,"getIdForRefSchema",{enumerable:!0,get:function(){return Mi.getIdForRefSchema}});Object.defineProperty(f,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Mi.getIdForRequestBodySchema}});Object.defineProperty(f,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Mi.getRawOperationDataIdentifierName}});Object.defineProperty(f,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Mi.sanitizedIdentifierName}})});var D_=g(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.BaseCryptoBeta=qn.supportedDigests=void 0;qn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var qp=class{static{s(this,"BaseCryptoBeta")}};qn.BaseCryptoBeta=qp});var U_=g(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.WorkerCryptoBeta=void 0;var $p=D_(),mC=L(),jp=class extends $p.BaseCryptoBeta{static{s(this,"WorkerCryptoBeta")}async digest(t,r){if(!$p.supportedDigests.includes(t.toLowerCase()))throw new mC.RuntimeError(`Algorithm ${t} is not supported. Try using ${$p.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};wc.WorkerCryptoBeta=jp});var k_=g(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.BaseKeyValueStore=void 0;var Vp=class{static{s(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};vc.BaseKeyValueStore=Vp});var H_=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.WorkerKeyValueStore=void 0;var M_=L(),yC=k_(),Gp=class extends yC.BaseKeyValueStore{static{s(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new M_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new M_.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Tc.WorkerKeyValueStore=Gp});var Lt=g(dt=>{"use strict";var gC=dt&&dt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),bC=dt&&dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&gC(t,e,r)};Object.defineProperty(dt,"__esModule",{value:!0});dt.KeyValueStore=dt.CryptoBeta=void 0;bC(L_(),dt);var _C=U_();Object.defineProperty(dt,"CryptoBeta",{enumerable:!0,get:function(){return _C.WorkerCryptoBeta}});var EC=H_();Object.defineProperty(dt,"KeyValueStore",{enumerable:!0,get:function(){return EC.WorkerKeyValueStore}})});var AL={};Xi(AL,{GraphQLComplexityLimitInboundPolicy:()=>yE,GraphQLDisableIntrospectionInboundPolicy:()=>bE});module.exports=eo(AL);var Zn=yh(Lt());function B(e,t){if(!!!e)throw new Error(t)}s(B,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}s(Ee,"isObjectLike");function At(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}s(At,"invariant");var wC=/\r\n|[\n\r]/g;function $n(e,t){let r=0,n=1;for(let i of e.body.matchAll(wC)){if(typeof i.index=="number"||At(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}s($n,"getLocation");function Bp(e){return Sc(e.source,$n(e.source,e.start))}s(Bp,"printLocation");function Sc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,o=e.locationOffset.line-1,a=t.line+o,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
74
+ `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new kr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}s(eR,"validateComputedSignature");function tR(e,t){return typeof e!="string"?null:e.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===t&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}s(tR,"parseHeader");function rR(e,t){if(e.length!==t.length)return!1;let r=e.length,n=0;for(let i=0;i<r;++i)n|=e.charCodeAt(i)^t.charCodeAt(i);return n===0}s(rR,"secureCompare");async function Fg(e,t){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(e)),o=new Uint8Array(i),a=new Array(o.length);for(let c=0;c<o.length;c++)a[c]=ip[o[c]];return a.join("")}s(Fg,"computeHMACSignatureAsync");Nn.computeHMACSignatureAsync=Fg;var ip=new Array(256);for(let e=0;e<ip.length;e++)ip[e]=e.toString(16).padStart(2,"0")});var qt=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.optionValidator=void 0;var Ai=L();function nR(e,t){let r=s((o,a,c)=>{let u=e[o];if(!(c&&u===void 0)){if(u===void 0)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Ai.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=s((o,a)=>(r(o,a,!0),{optional:n,required:i}),"optional"),i=s((o,a)=>(r(o,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}s(nR,"optionValidator");da.optionValidator=nR});var op=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.StripeWebhookVerificationInboundPolicy=void 0;var iR=se(),oR=qg(),sR=qt(),aR=s(async(e,t,r,n)=>{(0,sR.optionValidator)(r,n).required("signingSecret","string").optional("tolerance","number");let i=e.headers.get("stripe-signature");try{let o=await e.clone().text();await(0,oR.constructEventAsync)(o,i,r.signingSecret)}catch(o){return t.log.error("Error validating stripe webhook",o),iR.HttpProblems.badRequest(e,t,{title:"Webhook Error",detail:o.message})}return e},"StripeWebhookVerificationInboundPolicy");pa.StripeWebhookVerificationInboundPolicy=aR});var $g=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.MeteringPlugin=void 0;var cR=gt(),sp=class extends cR.SystemRuntimePlugin{static{s(this,"MeteringPlugin")}};ha.MeteringPlugin=sp});var Vg=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.StripeMeteringPlugin=void 0;var jg=yn(),lt=L(),uR=Ct(),lR=op(),xn=se(),dR=Yt(),pR=zr(),hR=Uu(),fR=ot(),ap=Y(),cp=Dt(),mR=$g(),yR="checkout.session.completed",up=class extends mR.MeteringPlugin{static{s(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=s(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l}=this.options;if(!l)if(jg.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=jg.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new lt.ConfigurationError("StripeMeteringPlugin - No 'meteringBucketId' property provided");let d=this.options.meteringBucketRegion??"us-central1";if(!wR(d))throw new lt.ConfigurationError(`StripeMeteringPlugin - The value '${d}' on the property 'meteringBucketRegion' is invalid.`);let p=await c.json();if(!ER(p))return xn.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});u.log.info(`Received Stripe webhook event of type '${p.type}' with ID '${p.id}'.`);let m;try{m=await gR({event:p,stripeSecretKey:this.options.stripeSecretKey,logger:u.log})}catch(h){return xn.HttpProblems.internalServerError(c,u,{detail:h.message??"Unknown error getting subscription info"})}if(m){let h;if(this.options.apiKeyBucketName&&ap.Environment.instance.build.ACCOUNT_NAME&&this.options.zuploAccountApiKey?h=await bR({bucketName:this.options.apiKeyBucketName,accountName:ap.Environment.instance.build.ACCOUNT_NAME,stripeProductId:m.productId,stripeSubscriptionId:m.subscriptionId,stripeCustomerId:m.customerId,managerEmail:m.customerEmail,zuploAccountApiKey:this.options.zuploAccountApiKey,logger:u.log}):u.log.debug("Skipping consumer creation. No 'apiKeyBucketName', 'zuploAccountApiKey', or account variable set."),!h)return xn.HttpProblems.internalServerError(c,u,{detail:"No consumer was created, skipping creation of subscription"});let y="routes.oas.json";return _R({request:c,context:u,stripeProductId:m.productId,stripeSubscriptionId:m.subscriptionId,customerKey:h,productKey:y,meteringBucketId:l,meteringBucketRegion:d})}return xn.HttpProblems.ok(c,u,{detail:"Event was ignored by Stripe metering plugin webhook."})},"stripeWebhookHandler"),i=(0,pR.createInternalPolicyProcessor)({inboundPolicies:[{handler:lR.StripeWebhookVerificationInboundPolicy,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),o=new uR.Pipeline({processors:[dR.metricsProcessor,i],handler:n,gateway:r}),a=new fR.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:hR.SystemRouteName.StripePlugin});t.addRoute(a,o.execute)}};fa.StripeMeteringPlugin=up;async function gR({event:e,stripeSecretKey:t,logger:r}){let n;if(e.type===yR){let l=e,d=l.data?.object?.subscription;if(!d)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");if(!l.data?.object?.client_reference_id)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");let m=await fetch(`https://api.stripe.com/v1/subscriptions/${d}`,{headers:{Authorization:`Bearer ${t}`}}),h=await m.json();if(m.status!==200){let y="Error retrieving subscription from Stripe API.";throw r.error(y,h),new lt.RuntimeError(y)}n=h}if(!n)return;let i=n.id;if(!i)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID.");let o=n.items?.data.find(l=>l.object==="subscription_item");if(!o||!o.id)throw new Error("Invalid Stripe Webhook event. Expected '.data.object.items.data[]' to contain a subscription_item.");let a=o.plan;if(!a||!a.product)throw new lt.RuntimeError("Invalid Stripe Webhook event. Expected '.data.object.items.data[].plan'.");let c=await fetch(`https://api.stripe.com/v1/customers/${n.customer}`,{headers:{Authorization:`Bearer ${t}`}}),u=await c.json();if(c.status!==200){let l="Error retrieving customer from Stripe API.";throw r.error(l,u),new lt.RuntimeError(l)}return{subscriptionId:i,productId:a.product,customerId:n.customer,customerEmail:u.email}}s(gR,"getStripeSubscription");async function bR({accountName:e,bucketName:t,zuploAccountApiKey:r,stripeSubscriptionId:n,stripeProductId:i,stripeCustomerId:o,managerEmail:a,logger:c}){let u=new URL(`/v1/accounts/${e}/key-buckets/${t}/consumers`,"https://dev.zuplo.com");u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:`Consumer for Stripe subscription ${n}`,tags:{providerSubscriptionKey:n,planProviderKey:i},metadata:{stripeSubscriptionId:n,stripeProductId:i,stripeCustomerId:o},managers:[a]},p=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw c.error(h,m),new lt.RuntimeError(h)}return c.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:n,stripeProductId:i}),l}s(bR,"createConsumer");async function _R({request:e,context:t,stripeSubscriptionId:r,stripeProductId:n,customerKey:i,productKey:o,meteringBucketId:a,meteringBucketRegion:c}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:c,providerKey:r,planProviderKey:n,customerKey:i,productKey:o};try{let{authApiJWT:l,meteringServiceUrl:d}=ap.Environment.instance;if(!(0,cp.isNonEmptyString)(l))throw new lt.SystemError("No Zuplo JWT token set.");let p=await fetch(`${d}/internal/v1/metering/${a}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let m="Error creating metering subscription.",h;try{h=await p.json()}catch{h={status:p.status,statusText:p.statusText}}throw t.log.error(m,h),new lt.RuntimeError(m)}}catch(l){return xn.HttpProblems.internalServerError(e,t,{detail:l.message})}return t.log.info("Successfully created/updated metering subscription.",u),xn.HttpProblems.ok(e,t)}s(_R,"saveSubscription");function ER(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,cp.isString)(e.id)&&"type"in e&&(0,cp.isString)(e.type)}s(ER,"isStripeWebhookEvent");function wR(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}s(wR,"isMetricsRegion")});var zg=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.AmberfloMeteringInboundPolicy=Cn.AmberfloMeteringPolicy=void 0;var Gg=L(),vR=ve(),Bg=ii(),Jg=new WeakMap,Kg={},lp=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){Jg.set(t,r)}};Cn.AmberfloMeteringPolicy=lp;async function TR(e,t,r,n){if(!r.statusCodes)throw new Gg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,Bg.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async o=>{if(i.includes(o.status)){let a=Jg.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new Gg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,Bg.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},m=Kg[r.apiKey];if(!m){let h=r.apiKey,y=e.headers.get("zm-test-id")??"";m=new vR.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),Kg[h]=m}m.enqueue(p),t.waitUntil(m.waitUntilFlushed())}}),e}s(TR,"AmberfloMeteringInboundPolicy");Cn.AmberfloMeteringInboundPolicy=TR});var dp=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.sha256=void 0;async function SR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}s(SR,"sha256");ma.sha256=SR});var $t=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.getPolicyCacheName=void 0;var IR=dp(),Wg=new Map;async function PR(e,t){let r,n=Wg.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,IR.sha256)(JSON.stringify({policyName:e,options:t}))}`,Wg.set(e,r)),r}s(PR,"getPolicyCacheName");ya.getPolicyCacheName=PR});var mp=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.ApiKeyInboundPolicy=void 0;var AR=$t(),RR=Jt(),Qg=yn(),pp=L(),OR=Lt(),hp=Le(),fp=Y(),NR=Is(),Yg="key-metadata-cache-type";function xR(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}s(xR,"getKeyValue");async function CR(e,t,r,n){if(!r.bucketName)if(Qg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=Qg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new pp.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new pp.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let o=s(T=>i.allowUnauthenticatedRequests?e:OR.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return o("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return o("Invalid Authorization Scheme");let c=xR(a,i);if(!c||c==="")return o("No key present");let u=await LR(c),l=await(0,AR.getPolicyCacheName)(n,i),d=new RR.MemoryZoneReadThroughCache(l,{logger:hp.SystemLogMap.getLogger(t)}),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==Yg&&hp.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),o("Authorization Failed");let m={key:c},h=await(0,NR.fetchRetry)({retryDelayMs:5,retries:2,logger:hp.SystemLogMap.getLogger(t)},`${fp.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":fp.Environment.instance.deploymentName??"unknown","User-Agent":fp.Environment.instance.systemUserAgent},body:JSON.stringify(m)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),o("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new pp.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),v={isValid:!0,typeId:Yg,user:{sub:y.name,data:y.metadata}};return e.user=v.user,d.put(u,v,i.cacheTtlSeconds),e}s(CR,"ApiKeyInboundPolicy");ga.ApiKeyInboundPolicy=CR;async function LR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(LR,"hashValue")});var Zg=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ApiAuthKeyInboundPolicy=void 0;var DR=mp();ba.ApiAuthKeyInboundPolicy=DR.ApiKeyInboundPolicy});var jt=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.OpenIdJwtInboundPolicy=void 0;var gp=(Ts(),eo(vs)),bp=L(),UR=se(),yp={},kR=s(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new bp.ConfigurationError("Invalid State - jwkUrl not set");yp[t.jwkUrl]||(yp[t.jwkUrl]=(0,gp.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,gp.jwtVerify)(e,yp[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),MR=s(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let o=new TextEncoder().encode(t.secret);r=new Uint8Array(o)}else r=t.secret;let{payload:n}=await(0,gp.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),HR=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),o="bearer ",a=s(m=>UR.HttpProblems.unauthorized(e,t,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new bp.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new bp.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?kR:MR,l=await s(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(o)!==0)return a("Invalid bearer token format for authorization header");let m=i.substring(o.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(h){let y=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${y.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");_a.OpenIdJwtInboundPolicy=HR});var Xg=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.Auth0JwtInboundPolicy=void 0;var FR=jt(),qR=s(async(e,t,r,n)=>(0,FR.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Ea.Auth0JwtInboundPolicy=qR});var eb=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.BasicAuthInboundPolicy=void 0;var $R=se(),jR=s(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",o=s(l=>$R.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!n)return await o("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await o("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await o("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await o("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===h);return y||await o("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");wa.BasicAuthInboundPolicy=jR});var tb=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.CachingInboundPolicy=void 0;var VR=$t(),GR=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function BR(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(BR,"digestMessage");var KR=s(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await BR(JSON.stringify(n)),o=new URL(e.url),a=new URLSearchParams(o.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${o.origin}${o.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function JR(e,t,r,n){let i=await(0,VR.getPolicyCacheName)(n,r),o=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await KR(e,r),u=await o.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let m=r?.expirationSecondsTtl??60,h=new Response(p.body,p);GR.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${m}`),t.waitUntil(o.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}s(JR,"CachingInboundPolicy");va.CachingInboundPolicy=JR});var rb=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ChangeMethodInboundPolicy=void 0;var zR=L(),WR=He(),QR=s(async(e,t,r,n)=>{if(!r.method)throw new zR.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new WR.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");Ta.ChangeMethodInboundPolicy=QR});var nb=g(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.ClearHeadersInboundPolicy=void 0;var YR=He(),ZR=s(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new YR.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");Sa.ClearHeadersInboundPolicy=ZR});var ib=g(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.ClearHeadersOutboundPolicy=void 0;var XR=s(async(e,t,r,n)=>{let i=[...n.exclude??[]],o=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&o.set(c,u)}),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");Ia.ClearHeadersOutboundPolicy=XR});var ob=g(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.ClerkJwtInboundPolicy=void 0;var e0=jt(),t0=s(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),o=new URL(i);return o.pathname="/.well-known/jwks.json",(0,e0.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:o.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");Pa.ClerkJwtInboundPolicy=t0});var ab=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.CognitoJwtInboundPolicy=void 0;var sb=L(),r0=jt(),n0=s(async(e,t,r,n)=>{if(!r.userPoolId)throw new sb.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new sb.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,r0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");Aa.CognitoJwtInboundPolicy=n0});var ub=g(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.CompositeInboundPolicy=void 0;var i0=L(),o0=mn(),cb=zr(),s0=s(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new i0.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=o0.Gateway.instance,o=(0,cb.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,cb.toStackedInboundHandler)(o)(e,t)},"CompositeInboundPolicy");Ra.CompositeInboundPolicy=s0});var db=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.CreditsMeteringInboundPolicy=void 0;var Ri=se(),lb=Y(),a0=s(async(e,t,r)=>{let n=e.user;if(!n)return Ri.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return Ri.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let o=r.bucketId,a=await c0(o,i,t);if(!a)return Ri.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return Ri.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return Ri.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await u0(o,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");Oa.CreditsMeteringInboundPolicy=a0;async function c0(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=lb.Environment.instance,o=new URL(`${i}/internal/v1/metering/${e}/subscriptions`);o.search=new URLSearchParams({customerKey:t,status:"active"}).toString();let a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`,"zp-rid":r.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}s(c0,"getSubscription");async function u0(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=lb.Environment.instance,a=new URL(`${o}/internal/v1/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}s(u0,"consumeSubscription")});var pb=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.CurityPhantomTokenInboundPolicy=void 0;var l0=$t(),d0=Jt(),Na=se(),p0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return Na.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let o=h0(i);if(!o)return Na.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,l0.getPolicyCacheName)(n,r),c=new d0.MemoryZoneReadThroughCache(a,t),u=await c.get(o);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+o+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(o,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),Na.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):Na.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");xa.CurityPhantomTokenInboundPolicy=p0;function h0(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}s(h0,"getToken")});var hb=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.FirebaseJwtInboundPolicy=void 0;var f0=qt(),m0=jt(),y0=s(async(e,t,r,n)=>((0,f0.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,m0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");Ca.FirebaseJwtInboundPolicy=y0});var fb=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.FormDataToJsonInboundPolicy=void 0;var g0=He(),b0=s(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",o=e.headers.get("content-type")?.toLowerCase();if(!o||![i,n].includes(o))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new g0.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");La.FormDataToJsonInboundPolicy=b0});var mb=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.GeoFilterInboundPolicy=void 0;var _0=L(),E0=se(),Ln="__unknown__",w0=s(async(e,t,r,n)=>{let i={allow:{countries:Un(r.allow?.countries,"allow.countries",n),regionCodes:Un(r.allow?.regionCodes,"allow.regionCode",n),asns:Un(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Un(r.block?.countries,"block.countries",n),regionCodes:Un(r.block?.regionCodes,"block.regionCode",n),asns:Un(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},o=t.incomingRequestProperties.country?.toLowerCase()??Ln,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Ln,c=t.incomingRequestProperties.asn?.toString()??Ln,u=i.ignoreUnknown&&o===Ln,l=i.ignoreUnknown&&a===Ln,d=i.ignoreUnknown&&c===Ln,p=i.allow.countries,m=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(o)&&!u||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Dn(e,t,n,o,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(o)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Dn(e,t,n,o,a,c):e},"GeoFilterInboundPolicy");Da.GeoFilterInboundPolicy=w0;function Dn(e,t,r,n,i,o){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${o}')`),E0.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:o}})}s(Dn,"blockedResponse");function Un(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new _0.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}s(Un,"toLowerStringArray")});var yb=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.JWTScopeValidationInboundPolicy=void 0;var v0=s(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!s((o,a)=>a.every(c=>o.includes(c)),"scopeChecker")(n,r.scopes)){let o={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(o),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");Ua.JWTScopeValidationInboundPolicy=v0});var bb=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.MockApiInboundPolicy=void 0;var T0=se(),S0=s(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return _p(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let o=Object.keys(i),a=[];if(o.length===0)return _p(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(o.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return gb(a[c])}else return a.length>0?gb(a[0]):_p(n,e,t,"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");ka.MockApiInboundPolicy=S0;function gb(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}s(gb,"generateResponse");var _p=s((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return T0.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Tb=g(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.MoesifInboundPolicy=kn.setMoesifContext=void 0;var I0=L(),P0=ve(),A0="Incoming",R0={logRequestBody:!0,logResponseBody:!0};function _b(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}s(_b,"headersToObject");function Eb(){return new Date().toISOString()}s(Eb,"timestamp");var Ep=new WeakMap,O0={};function N0(e,t){let r=Ep.get(e);r||(r=O0);let n=Object.assign({...r},t);Ep.set(e,n)}s(N0,"setMoesifContext");kn.setMoesifContext=N0;async function wb(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}s(wb,"readBody");var x0={},wp;function vb(){if(!wp)throw new I0.RuntimeError("Invalid State - no _lastLogger");return wp}s(vb,"getLastLogger");function C0(e){let t=x0[e];return t||(t=new P0.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);vb().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||vb().error({status:i.status,body:await i.text()})})),t}s(C0,"getDispatcher");async function L0(e,t,r,n){wp=t.log;let i=Eb(),o=Object.assign(R0,r);if(!o.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=o.logRequestBody?await wb(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=C0(o.applicationId),d=e.headers.get("true-client-ip"),p=Ep.get(t)??{},m={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:_b(e.headers)},h=o.logResponseBody?await wb(c,t):void 0,y={time:Eb(),status:c.status,headers:_b(c.headers),body:h},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:A0};l.enqueue(v),t.waitUntil(l.waitUntilFlushed())}),e}s(L0,"MoesifInboundPolicy");kn.MoesifInboundPolicy=L0});var Sb=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.OktaJwtInboundPolicy=void 0;var D0=jt(),U0=s(async(e,t,r,n)=>(0,D0.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Ma.OktaJwtInboundPolicy=U0});var Ib=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.PropelAuthJwtInboundPolicy=void 0;var k0=(Ts(),eo(vs)),M0=jt(),vp,H0=s(async(e,t,r,n)=>{if(!vp)try{vp=await(0,k0.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,M0.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:vp,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ha.PropelAuthJwtInboundPolicy=H0});var Pb=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var je=Dt(),et=class extends Error{static{s(this,"ValidationError")}constructor(t){super(t)}};G.ValidationError=et;var Oi=class extends et{static{s(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};G.ArgumentUndefinedError=Oi;var Ni=class extends et{static{s(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};G.ArgumentTypeError=Ni;function F0(e,t){if((0,je.isUndefined)(e))throw new Oi(t)}s(F0,"throwIfUndefined");G.throwIfUndefined=F0;function Tp(e,t){if((0,je.isUndefinedOrNull)(e))throw new Oi(t)}s(Tp,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Tp;function q0(e,t){if(Tp(e,t),!(0,je.isString)(e))throw new Ni(t,"string")}s(q0,"throwIfNotString");G.throwIfNotString=q0;function $0(e,t){if(Tp(e,t),!(0,je.isNumber)(e))throw new Ni(t,"number")}s($0,"throwIfNotNumber");G.throwIfNotNumber=$0;var xi=class extends et{static{s(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};G.OptionUndefinedError=xi;var Mn=class extends et{static{s(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=Mn;function j0(e,t,r,n){if((0,je.isUndefined)(n))throw new xi(e,t,r)}s(j0,"throwIfOptionUndefined");G.throwIfOptionUndefined=j0;function Fa(e,t,r,n){if((0,je.isUndefinedOrNull)(n))throw new xi(e,t,r)}s(Fa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Fa;function V0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isString)(n))throw new Mn(e,t,r,"string")}s(V0,"throwIfOptionNotString");G.throwIfOptionNotString=V0;function G0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isNumber)(n))throw new Mn(e,t,r,"number")}s(G0,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=G0;function B0(e,t,r,n){if(Fa(e,t,r,n),!(0,je.isObject)(n))throw new Mn(e,t,r,"object")}s(B0,"throwIfOptionNotObject");G.throwIfOptionNotObject=B0;function K0(e,t){if((0,je.isUndefined)(e))throw new et(t)}s(K0,"throwIfStateUndefined");G.throwIfStateUndefined=K0;function qa(e,t){if((0,je.isUndefinedOrNull)(e))throw new et(t)}s(qa,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=qa;function J0(e,t){if(qa(e,t),!(0,je.isString)(e))throw new et(t);return!0}s(J0,"throwIfStateNotString");G.throwIfStateNotString=J0;function z0(e,t){if(qa(e,t),!(0,je.isNumber)(e))throw new et(t);return!0}s(z0,"throwIfStateNotNumber");G.throwIfStateNotNumber=z0;function W0(e,t){if(qa(e,t),!(0,je.isObject)(e))throw new et(t);return!0}s(W0,"throwIfStateNotObject");G.throwIfStateNotObject=W0});var Ab=g(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.InMemoryRedisClient=Hn.StandardRedisClient=void 0;var Sp=L(),$a=Pb(),Ip=class e{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,$a.throwIfNotString)(t,"redisClientUrl"),(0,$a.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,$a.throwIfNotString)(t,"url");let o=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=o.headers.get("Content-Type")?.includes("application/json")?await o.json():await o.text();if(o.ok)return a;throw o.status===401?new Sp.SystemError("Redis client failed with 401: Unauthorized"):new Sp.SystemError(`Redis client failed with (${o.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Hn.StandardRedisClient=Ip;var Pp=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,$a.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:o,key:a}=JSON.parse(r),c=Date.now()+o*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Sp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Hn.InMemoryRedisClient=Pp});var Cb=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.RateLimitInboundPolicy=void 0;var Q0=Sr(),Y0=$t(),Z0=oo(),Vt=L(),X0=se(),Rb=Le(),Ci=Y(),Ob=Ab(),Nb=Dt(),ja=(0,Q0.debug)("zuplo:policies:RateLimitInboundPolicy"),eO="strict",tO=s(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),rO=s(async e=>({key:`ip-${tO(e)}`}),"getIP"),nO=s(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),iO=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Va;function oO(e,t){let r;if(Va)return Va;if(Ci.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Ob.InMemoryRedisClient,Va=r,r;let{authApiJWT:n,redisURL:i}=Ci.Environment.instance;if(!(0,Nb.isString)(i))throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,Nb.isString)(n))throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Ob.StandardRedisClient.initialize(i,n,Ci.Environment.instance.deploymentName??"unknown",Ci.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Vt.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Va=r,r}s(oO,"getRedisClient");async function xb(e,t,r,n,i){let o=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:i})}s(xb,"getCountAndUpdateExpiry");function sO(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new Vt.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,o,a)=>{let c=await r(i,o,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw o.log.error(u),new Vt.RuntimeError(u)}return c},"outerFunction")}s(sO,"wrapUserFunction");var aO="Retry-After",cO=s(async(e,t,r,n)=>{let i=Date.now(),o=Rb.SystemLogMap.getLogger(t),a=s((u,l)=>{if(r.throwOnFailure)throw new Vt.SystemError(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[aO]=l.toString()),X0.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:sO(r,n),user:nO,ip:rO,all:iO}[r.rateLimitBy],d=await l(e,t,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=oO(n,o),S=`bucket/${Ci.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??eO)==="async"){let C=await(0,Y0.getPolicyCacheName)(n,r),re=new Z0.ZoneCache(C,{logger:Rb.SystemLogMap.getLogger(t)}),ne=xb(S,h,v,o,t.requestId),me=await re.get(S);if(me!==void 0&&me<=Date.now()){ja(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Be=Math.round((me-Date.now())/1e3);return c(y,Be)}return t.addEventListener("responseSending",Be=>{try{let E=Be,H=E.mutableResponse;E.mutableResponse=(async()=>{let Ce=await ne;if(Ce.count>m){let ou=Date.now()+Ce.ttlSeconds*1e3;return re.put(S,ou,Ce.ttlSeconds).catch(fh=>{throw o.error(fh),fh}),ja(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(y,Ce.ttlSeconds)}return H})()}catch(E){o.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let j=await xb(S,h,v,o,t.requestId);return j.count>m?(ja(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(y,j.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;ja(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Ga.RateLimitInboundPolicy=cO});var kb=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.ReadmeMetricsInboundPolicy=void 0;var uO=ve(),Ap=Y(),Lb=ii(),Rp;function Db(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}s(Db,"headersToNameValuePairs");function lO(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}s(lO,"queryToNameValueParis");function dO(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}s(dO,"parseIntOrUndefined");var Ub={};async function pO(e,t,r,n){let i=new Date,o=Date.now();return Rp||(Rp={name:"zuplo",version:Ap.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Ap.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,Lb.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,Lb.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Ap.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:Rp,entries:[{startedDateTime:i.toISOString(),time:Date.now()-o,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:Db(e.headers),queryString:lO(e.query)},response:{status:a.status,statusText:a.statusText,headers:Db(a.headers),content:{size:dO(e.headers.get("content-length"))}}}]}}},d=Ub[r.apiKey];if(!d){let p=r.apiKey;d=new uO.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),Ub[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}s(pO,"ReadmeMetricsInboundPolicy");Ba.ReadmeMetricsInboundPolicy=pO});var Mb=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.RemoveHeadersInboundPolicy=void 0;var hO=L(),fO=He(),mO=s(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new hO.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let o=new Headers(e.headers);return i.forEach(c=>{o.delete(c)}),new fO.ZuploRequest(e,{headers:o})},"RemoveHeadersInboundPolicy");Ka.RemoveHeadersInboundPolicy=mO});var Hb=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.RemoveHeadersOutboundPolicy=void 0;var yO=L(),gO=s(async(e,t,r,n,i)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new yO.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return o.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Ja.RemoveHeadersOutboundPolicy=gO});var Fb=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.RemoveQueryParamsInboundPolicy=void 0;var bO=L(),_O=He(),EO=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new bO.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let o=new URL(e.url);return i.forEach(c=>{o.searchParams.delete(c)}),new _O.ZuploRequest(o.toString(),e)},"RemoveQueryParamsInboundPolicy");za.RemoveQueryParamsInboundPolicy=EO});var qb=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ReplaceStringOutboundPolicy=void 0;var wO=s(async(e,t,r,n)=>{let i=await e.text(),o=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(o,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Wa.ReplaceStringOutboundPolicy=wO});var jb=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.RequestSizeLimitInboundPolicy=void 0;var $b=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),vO=s(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),o=i!==null?parseInt(i):void 0;return o&&!isNaN(o)&&o>r.maxSizeInBytes?$b():o&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?$b():e},"RequestSizeLimitInboundPolicy");Qa.RequestSizeLimitInboundPolicy=vO});var Ya=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function TO(e,t,r){return`_${Mr(e+"_"+t+"_"+r)}`}s(TO,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=TO;function SO(e,t,r,n){return`_${Mr(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}s(SO,"getIdForParameterSchema");tt.getIdForParameterSchema=SO;function IO(e,t,r){return`_${Mr(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Mr(r.toLowerCase())}`}s(IO,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=IO;function PO(e,t){return`_${Mr(e)}__${Mr(t)}`}s(PO,"getIdForRefSchema");tt.getIdForRefSchema=PO;function Mr(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}s(Mr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Mr});var Li=g(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.getErrorsFromValidator=De.shouldReject=De.shouldLog=De.logErrors=De.validateParameters=De.getParametersForOperation=void 0;var AO=mn(),RO=Ya(),OO=s(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");De.getParametersForOperation=OO;var NO=s((e,t,r,n,i)=>{let o=[],a=!0,c=[];return e.forEach(u=>{if(u.required&&!t[u.name])a=!1,o.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,RO.getIdForParameterSchema)(r,n,i,u.name),d=AO.Gateway.instance.schemaValidator[l],p=d(t[u.name]),m=(0,De.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),o.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:o}},"validateParameters");De.validateParameters=NO;var xO=s((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");De.logErrors=xO;var CO=s(e=>e==="log-only"||e==="reject-and-log","shouldLog");De.shouldLog=CO;var LO=s(e=>e==="reject-only"||e==="reject-and-log","shouldReject");De.shouldReject=LO;var DO=s(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");De.getErrorsFromValidator=DO});var Vb=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.handleBodyValidation=void 0;var UO=mn(),Za=se(),kO=Ya(),Je=Li();async function MO(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let y=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,v=Za.HttpProblems.badRequest(t,e,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",y,[n],h),(0,Je.shouldReject)(r.validateBody))return v}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,y=Za.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?y:void 0}let i=t.headers.get("Content-Type"),o=i.indexOf(";");o>-1&&(i=i.substring(0,o));let a=(0,kO.getIdForRequestBodySchema)(e.route.path,t.method,i),c=UO.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,y=Za.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),m=Za.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return m}s(MO,"handleBodyValidation");Xa.handleBodyValidation=MO});var Gb=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.handleHeadersValidation=void 0;var HO=se(),Di=Li();function FO(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,Di.getParametersForOperation)(e),o=(0,Di.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!o.isValid){let a="Header validation failed",c=HO.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:o.errors});if((0,Di.shouldLog)(r.validateHeaders)&&(0,Di.logErrors)(e,r.logLevel??"info",a,o.invalidValues,o.errors),(0,Di.shouldReject)(r.validateHeaders))return c}}s(FO,"handleHeadersValidation");ec.handleHeadersValidation=FO});var Bb=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.handlePathParameterValidation=void 0;var qO=se(),Ui=Li();function $O(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Ui.getParametersForOperation)(e),i=(0,Ui.validateParameters)(n.filter(o=>o.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let o="Path parameters validation failed",a=qO.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Ui.shouldLog)(r.validatePathParameters)&&(0,Ui.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Ui.shouldReject)(r.validatePathParameters))return a}}s($O,"handlePathParameterValidation");tc.handlePathParameterValidation=$O});var Kb=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.handleQueryParameterValidation=void 0;var jO=se(),ki=Li();function VO(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,ki.getParametersForOperation)(e),i=(0,ki.validateParameters)(n.filter(o=>o.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let o="Query parameters validation failed",a=jO.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,ki.shouldLog)(r.validateQueryParameters)&&(0,ki.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,ki.shouldReject)(r.validateQueryParameters))return a}}s(VO,"handleQueryParameterValidation");rc.handleQueryParameterValidation=VO});var Jb=g(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.SchemaBasedRequestValidation=Hr.RequestValidationInboundPolicy=void 0;var GO=Vb(),BO=Gb(),KO=Bb(),JO=Kb(),zO=s(async(e,t,r)=>{let n=(0,JO.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,KO.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,BO.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,GO.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Hr.RequestValidationInboundPolicy=zO;Hr.SchemaBasedRequestValidation=Hr.RequestValidationInboundPolicy});var zb=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.RequireOriginInboundPolicy=void 0;var WO=L(),QO=se(),YO=s(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new WO.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let o=e.headers.get("origin");if(!o||!i.includes(o)){let a=r.failureDetail??"Forbidden";return QO.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");nc.RequireOriginInboundPolicy=YO});var Wb=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.SetBodyInboundPolicy=void 0;var ZO=He(),XO=s(async(e,t,r)=>new ZO.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");ic.SetBodyInboundPolicy=XO});var Yb=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.SetHeadersInboundPolicy=void 0;var Qb=L(),eN=He(),tN=s(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new Qb.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let o=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new Qb.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.has(c.name)||u)&&o.set(c.name,c.value)}),new eN.ZuploRequest(e,{headers:o})},"SetHeadersInboundPolicy");oc.SetHeadersInboundPolicy=tN});var Xb=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.SetHeadersOutboundPolicy=void 0;var Zb=L(),rN=s(async(e,t,r,n,i)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new Zb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new Zb.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");sc.SetHeadersOutboundPolicy=rN});var t_=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.SetQueryParamsInboundPolicy=void 0;var e_=L(),nN=He(),iN=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new e_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let o=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new e_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.searchParams.has(c.name)||u)&&o.searchParams.set(c.name,c.value)}),new nN.ZuploRequest(o.toString(),e)},"SetQueryParamsInboundPolicy");ac.SetQueryParamsInboundPolicy=iN});var r_=g(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.SetStatusOutboundPolicy=void 0;var oN=s(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");cc.SetStatusOutboundPolicy=oN});var n_=g(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.SleepInboundPolicy=void 0;var sN=L(),aN=s(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),cN=s(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new sN.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await aN(r.sleepInMs),e},"SleepInboundPolicy");uc.SleepInboundPolicy=cN});var o_=g(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.SupabaseJwtInboundPolicy=void 0;var i_=L(),uN=se(),lN=He(),dN=qt(),pN=jt(),hN=s(async(e,t,r,n)=>{(0,dN.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},o=await(0,pN.OpenIdJwtInboundPolicy)(e,t,i,n);if(o instanceof Response)return o;if(!(o instanceof lN.ZuploRequest))throw new i_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return o;let c=e.user?.data.app_metadata;if(!c)throw new i_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?uN.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):o},"SupabaseJwtInboundPolicy");lc.SupabaseJwtInboundPolicy=hN});var a_=g(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var fN=$t(),mN=Jt(),s_=L(),yN=Le(),gN=Is(),bN=qt(),_N=s(async(e,t,r,n)=>{(0,bN.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,fN.getPolicyCacheName)(n,r),o=new mN.MemoryZoneReadThroughCache(i,{logger:yN.SystemLogMap.getLogger(t)}),a=await o.get(n);if(!a){let c=await EN(r,t);o.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");dc.UpstreamAzureAdServiceAuthInboundPolicy=_N;async function EN(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,gN.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let o=await n.text();t.log.error("Could not get token from Azure AD",o)}catch{}throw new s_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new s_.RuntimeError("Response returned from Azure AD is not in the expected format.")}s(EN,"getAccessToken")});var u_=g(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var wN=$t(),vN=Jt(),TN=L(),SN=Le(),Op=pn(),IN=qt(),c_="https://accounts.google.com/o/oauth2/token",Np,PN=s(async(e,t,r,n)=>{(0,IN.optionValidator)(r,n).required("serviceAccountJson","string"),Np||(Np=await Op.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},o=await(0,wN.getPolicyCacheName)(n,r),a=new vN.MemoryZoneReadThroughCache(o,{logger:SN.SystemLogMap.getLogger(t)}),c=await a.get(n);if(!c){let u=await(0,Op.getTokenFromGcpServiceAccount)({serviceAccount:Np,audience:c_,payload:i}),l=await(0,Op.exchangeGgpJwtForIdToken)(c_,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new TN.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");pc.UpstreamFirebaseAdminAuthInboundPolicy=PN});var l_=g(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var AN=$t(),RN=Jt(),Fn=L(),ON=Le(),NN=dp(),xp=pn(),xN=ii(),CN=qt(),LN="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",DN=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Cp,UN=s(async(e,t,r,n)=>{if((0,CN.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Fn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(DN.indexOf(p)!==-1)throw new Fn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Cp||(Cp=await xp.GcpServiceAccount.init(r.serviceAccountJson));let o=r.userId;if(!o&&!r.userIdPropertyPath){if(!e.user)throw new Fn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");o=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new Fn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);o=(0,xN.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!o)throw new Fn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,AN.getPolicyCacheName)(n,r),c=new RN.MemoryZoneReadThroughCache(a,{logger:ON.SystemLogMap.getLogger(t)}),u={uid:o,claims:i},l=await(0,NN.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,xp.getTokenFromGcpServiceAccount)({serviceAccount:Cp,audience:LN,payload:u}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,xp.exchangeFirebaseJwtForIdToken)(m,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new Fn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");hc.UpstreamFirebaseUserAuthInboundPolicy=UN});var p_=g(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.UpstreamGcpJwtInboundPolicy=void 0;var d_=pn(),kN=qt(),Lp,MN=s(async(e,t,r,n)=>{(0,kN.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Lp||(Lp=await d_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,d_.getTokenFromGcpServiceAccount)({serviceAccount:Lp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");fc.UpstreamGcpJwtInboundPolicy=MN});var f_=g(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.UpstreamGcpServiceAuthInboundPolicy=void 0;var HN=$t(),FN=pu(),qN=Jt(),$N=L(),Dp=pn(),jN=qt(),h_="https://www.googleapis.com/oauth2/v4/token",Up,VN=s(async(e,t,r,n)=>{(0,jN.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Up||(Up=await Dp.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,HN.getPolicyCacheName)(n,r),o;r.useMemoryCacheOnly?o=new FN.MemoryCache(i):o=new qN.MemoryZoneReadThroughCache(i,t);let a=await o.get(n);if(!a){let c=await(0,Dp.getTokenFromGcpServiceAccount)({serviceAccount:Up,audience:h_,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,Dp.exchangeGgpJwtForIdToken)(h_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new $N.RuntimeError("Invalid token response from GCP");a=u,o.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");mc.UpstreamGcpServiceAuthInboundPolicy=VN});var y_=g(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.ValidateJsonSchemaInbound=void 0;var GN=L(),m_=se(),BN=s(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return m_.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new GN.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return m_.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");yc.ValidateJsonSchemaInbound=BN});var __=g(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.MeteringInboundPolicy=void 0;var g_=Vs(),b_=yn(),gc=L(),KN=se(),JN=Le(),zN=Y(),WN=s(async(e,t,r,n)=>{let i=JN.SystemLogMap.getLogger(t);t.addResponseSendingFinalHook(async(d,p,m)=>{let h=g_.ContextData.get(m,"subscription");if((r.allowRequestsWithoutSubscription??!1)&&!h)return;if(!r.bucketId)if(b_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=b_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new gc.ConfigurationError(`MeteringInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:v,meteringServiceUrl:T}=zN.Environment.instance;d.ok&&h&&r.meters&&fetch(`${T}/internal/v1/metering/${r.bucketId}/subscriptions/${h.id}/quotas/consume`,{headers:{Authorization:`Bearer ${v}`,"zp-rid":m.requestId},method:"POST",body:JSON.stringify({meters:r.meters})}).catch(S=>{m.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`,S)})});let o=g_.ContextData.get(t,"subscription"),a=r.allowRequestsWithoutSubscription??!1,c=r.allowRequestsOverQuota??!1;if(!o){if(a)return e;throw new gc.ConfigurationError("Subscription is not available for user")}if(o&&Object.keys(o.quotas).length===0)throw new gc.ConfigurationError("Quota is not set up for the user's subscription");let l=Object.keys(r.meters).filter(d=>!Object.keys(o.quotas).includes(d));if(l.length>0)throw new gc.ConfigurationError(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(o.quotas))if(o.quotas[d]<=0&&!c)return KN.HttpProblems.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return e},"MeteringInboundPolicy");bc.MeteringInboundPolicy=WN});var w_=g(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.LoadSubscriptionInboundPolicy=void 0;var QN=Vs(),E_=yn(),YN=L(),kp=se(),ZN=Le(),XN=Y(),ex=s(async(e,t,r,n)=>{let i=ZN.SystemLogMap.getLogger(t),o=r.allowRequestsWithoutSubscription??!1,a=e.user;if(!a)return o?e:kp.HttpProblems.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!r.bucketId)if(E_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=E_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new YN.ConfigurationError(`LoadSubscriptionInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:c,meteringServiceUrl:u}=XN.Environment.instance,{sub:l}=a,d,p;try{if(d=await fetch(`${u}/internal/v1/metering/${r.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${c}`,"zp-rid":t.requestId},method:"GET"}),!d.ok)return t.log.error(await d.text()),kp.HttpProblems.forbidden(e,t);p=await d.json()}catch(h){i.error(`LoadSubscriptionInboundPolicy '${n}' -error in serviceResponse`,h)}if((!p||!p.data||p.data.length===0)&&!o)return kp.HttpProblems.unauthorized(e,t,{detail:"No valid, active subscription found"});if((!p||!p.data||p.data.length===0)&&o)return e;let m=p&&p.data?p.data[0]:void 0;return QN.ContextData.set(t,"subscription",m),e},"LoadSubscriptionInboundPolicy");_c.LoadSubscriptionInboundPolicy=ex});var v_=g(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.ServiceProviderImpl=void 0;var tx=L(),Mp=class e{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return e.#e||(e.#e=new e),e.#e}setInstance(t){e.#e=t}addService(t,r){if(this.services.get(t))throw new tx.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Ec.ServiceProviderImpl=Mp});var L_=g(f=>{"use strict";var rx=f&&f.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Hp=f&&f.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&rx(t,e,r)},nx=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});f.RateLimitInboundPolicy=f.BasicRateLimitInboundPolicy=f.PropelAuthJwtInboundPolicy=f.OpenIdJwtInboundPolicy=f.OktaJwtInboundPolicy=f.setMoesifContext=f.MoesifInboundPolicy=f.MockApiInboundPolicy=f.JWTScopeValidationInboundPolicy=f.GeoFilterInboundPolicy=f.FormDataToJsonInboundPolicy=f.FirebaseJwtInboundPolicy=f.CurityPhantomTokenInboundPolicy=f.CreditsMeteringInboundPolicy=f.CompositeInboundPolicy=f.CognitoJwtInboundPolicy=f.ClerkJwtInboundPolicy=f.ClearHeadersOutboundPolicy=f.ClearHeadersInboundPolicy=f.ChangeMethodInboundPolicy=f.CachingInboundPolicy=f.BasicAuthInboundPolicy=f.Auth0JwtInboundPolicy=f.ApiKeyInboundPolicy=f.ApiAuthKeyInboundPolicy=f.AmberfloMeteringPolicy=f.AmberfloMeteringInboundPolicy=f.AuditLogPlugin=f.AuditLogDataStaxProvider=f.HttpStatusCode=f.webSocketPipelineHandler=f.webSocketHandler=f.urlRewriteHandler=f.urlForwardHandler=f.redirectHandler=f.openApiSpecHandler=f.awsLambdaHandler=f.AwsLambdaHandlerExtensions=f.purgeGatewayCache=f.Handler=f.originalFetch=f.ConfigurationError=f.isZuploReadableEnvVariableName=f.isRestrictedEnvVariableName=f.environment=f.ContextData=f.ResponseSentEvent=f.ResponseSendingEvent=f.ZoneCache=f.MemoryZoneReadThroughCache=void 0;f.sanitizedIdentifierName=f.getRawOperationDataIdentifierName=f.getIdForRequestBodySchema=f.getIdForRefSchema=f.getIdForParameterSchema=f.SystemLogMap=f.httpStatuses=f.SYSTEM_LOGGER=f.API_KEY=f.ServiceProviderImpl=f.serialize=f.ContentTypes=f.Router=f.LookupResult=f.SystemRouteName=f.ZuploRequest=f.ProblemResponseFormatter=f.HttpProblems=f.LoadSubscriptionInboundPolicy=f.MeteringInboundPolicy=f.ValidateJsonSchemaInbound=f.UpstreamGcpServiceAuthInboundPolicy=f.UpstreamGcpJwtInboundPolicy=f.UpstreamFirebaseUserAuthInboundPolicy=f.UpstreamFirebaseAdminAuthInboundPolicy=f.UpstreamAzureAdServiceAuthInboundPolicy=f.SupabaseJwtInboundPolicy=f.StripeWebhookVerificationInboundPolicy=f.SleepInboundPolicy=f.SetStatusOutboundPolicy=f.SetQueryParamsInboundPolicy=f.SetHeadersOutboundPolicy=f.SetHeadersInboundPolicy=f.SetBodyInboundPolicy=f.RequireOriginInboundPolicy=f.SchemaBasedRequestValidation=f.RequestValidationInboundPolicy=f.RequestSizeLimitInboundPolicy=f.ReplaceStringOutboundPolicy=f.RemoveQueryParamsInboundPolicy=f.RemoveHeadersOutboundPolicy=f.RemoveHeadersInboundPolicy=f.ReadmeMetricsInboundPolicy=void 0;Eh();var ix=Jt();Object.defineProperty(f,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return ix.MemoryZoneReadThroughCache}});var ox=oo();Object.defineProperty(f,"ZoneCache",{enumerable:!0,get:function(){return ox.ZoneCache}});var T_=Ir();Object.defineProperty(f,"ResponseSendingEvent",{enumerable:!0,get:function(){return T_.ResponseSendingEvent}});Object.defineProperty(f,"ResponseSentEvent",{enumerable:!0,get:function(){return T_.ResponseSentEvent}});var sx=Vs();Object.defineProperty(f,"ContextData",{enumerable:!0,get:function(){return sx.ContextData}});var Fp=yn();Object.defineProperty(f,"environment",{enumerable:!0,get:function(){return Fp.environment}});Object.defineProperty(f,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return Fp.isRestrictedEnvVariableName}});Object.defineProperty(f,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return Fp.isZuploReadableEnvVariableName}});var ax=L();Object.defineProperty(f,"ConfigurationError",{enumerable:!0,get:function(){return ax.ConfigurationError}});var cx=Sd();Object.defineProperty(f,"originalFetch",{enumerable:!0,get:function(){return cx.originalFetch}});var S_=zy();Object.defineProperty(f,"Handler",{enumerable:!0,get:function(){return S_.Handler}});Object.defineProperty(f,"purgeGatewayCache",{enumerable:!0,get:function(){return S_.purgeGatewayCache}});var I_=dg();Object.defineProperty(f,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return I_.AwsLambdaHandlerExtensions}});Object.defineProperty(f,"awsLambdaHandler",{enumerable:!0,get:function(){return I_.awsLambdaHandler}});var ux=hg();Object.defineProperty(f,"openApiSpecHandler",{enumerable:!0,get:function(){return ux.openApiSpecHandler}});var lx=fg();Object.defineProperty(f,"redirectHandler",{enumerable:!0,get:function(){return lx.redirectHandler}});var dx=yg();Object.defineProperty(f,"urlForwardHandler",{enumerable:!0,get:function(){return dx.urlForwardHandler}});var px=bg();Object.defineProperty(f,"urlRewriteHandler",{enumerable:!0,get:function(){return px.urlRewriteHandler}});var hx=Eg();Object.defineProperty(f,"webSocketHandler",{enumerable:!0,get:function(){return hx.webSocketHandler}});var fx=Tg();Object.defineProperty(f,"webSocketPipelineHandler",{enumerable:!0,get:function(){return fx.webSocketPipelineHandler}});var mx=ku();Object.defineProperty(f,"HttpStatusCode",{enumerable:!0,get:function(){return mx.HttpStatusCode}});Hp(xg(),f);Hp(Dg(),f);var yx=Ug();Object.defineProperty(f,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return yx.AuditLogDataStaxProvider}});var gx=Mg();Object.defineProperty(f,"AuditLogPlugin",{enumerable:!0,get:function(){return gx.AuditLogPlugin}});Hp(Vg(),f);var P_=zg();Object.defineProperty(f,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return P_.AmberfloMeteringInboundPolicy}});Object.defineProperty(f,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return P_.AmberfloMeteringPolicy}});var bx=Zg();Object.defineProperty(f,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return bx.ApiAuthKeyInboundPolicy}});var _x=mp();Object.defineProperty(f,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return _x.ApiKeyInboundPolicy}});var Ex=Xg();Object.defineProperty(f,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return Ex.Auth0JwtInboundPolicy}});var wx=eb();Object.defineProperty(f,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return wx.BasicAuthInboundPolicy}});var vx=tb();Object.defineProperty(f,"CachingInboundPolicy",{enumerable:!0,get:function(){return vx.CachingInboundPolicy}});var Tx=rb();Object.defineProperty(f,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return Tx.ChangeMethodInboundPolicy}});var Sx=nb();Object.defineProperty(f,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return Sx.ClearHeadersInboundPolicy}});var Ix=ib();Object.defineProperty(f,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return Ix.ClearHeadersOutboundPolicy}});var Px=ob();Object.defineProperty(f,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return Px.ClerkJwtInboundPolicy}});var Ax=ab();Object.defineProperty(f,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return Ax.CognitoJwtInboundPolicy}});var Rx=ub();Object.defineProperty(f,"CompositeInboundPolicy",{enumerable:!0,get:function(){return Rx.CompositeInboundPolicy}});var Ox=db();Object.defineProperty(f,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return Ox.CreditsMeteringInboundPolicy}});var Nx=pb();Object.defineProperty(f,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return Nx.CurityPhantomTokenInboundPolicy}});var xx=hb();Object.defineProperty(f,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return xx.FirebaseJwtInboundPolicy}});var Cx=fb();Object.defineProperty(f,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return Cx.FormDataToJsonInboundPolicy}});var Lx=mb();Object.defineProperty(f,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return Lx.GeoFilterInboundPolicy}});var Dx=yb();Object.defineProperty(f,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return Dx.JWTScopeValidationInboundPolicy}});var Ux=bb();Object.defineProperty(f,"MockApiInboundPolicy",{enumerable:!0,get:function(){return Ux.MockApiInboundPolicy}});var A_=Tb();Object.defineProperty(f,"MoesifInboundPolicy",{enumerable:!0,get:function(){return A_.MoesifInboundPolicy}});Object.defineProperty(f,"setMoesifContext",{enumerable:!0,get:function(){return A_.setMoesifContext}});var kx=Sb();Object.defineProperty(f,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return kx.OktaJwtInboundPolicy}});var Mx=jt();Object.defineProperty(f,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return Mx.OpenIdJwtInboundPolicy}});var Hx=Ib();Object.defineProperty(f,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return Hx.PropelAuthJwtInboundPolicy}});var R_=Cb();Object.defineProperty(f,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return R_.RateLimitInboundPolicy}});Object.defineProperty(f,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return R_.RateLimitInboundPolicy}});var Fx=kb();Object.defineProperty(f,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return Fx.ReadmeMetricsInboundPolicy}});var qx=Mb();Object.defineProperty(f,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return qx.RemoveHeadersInboundPolicy}});var $x=Hb();Object.defineProperty(f,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return $x.RemoveHeadersOutboundPolicy}});var jx=Fb();Object.defineProperty(f,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return jx.RemoveQueryParamsInboundPolicy}});var Vx=qb();Object.defineProperty(f,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return Vx.ReplaceStringOutboundPolicy}});var Gx=jb();Object.defineProperty(f,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return Gx.RequestSizeLimitInboundPolicy}});var O_=Jb();Object.defineProperty(f,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return O_.RequestValidationInboundPolicy}});Object.defineProperty(f,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return O_.SchemaBasedRequestValidation}});var Bx=zb();Object.defineProperty(f,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return Bx.RequireOriginInboundPolicy}});var Kx=Wb();Object.defineProperty(f,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return Kx.SetBodyInboundPolicy}});var Jx=Yb();Object.defineProperty(f,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return Jx.SetHeadersInboundPolicy}});var zx=Xb();Object.defineProperty(f,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return zx.SetHeadersOutboundPolicy}});var Wx=t_();Object.defineProperty(f,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return Wx.SetQueryParamsInboundPolicy}});var Qx=r_();Object.defineProperty(f,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return Qx.SetStatusOutboundPolicy}});var Yx=n_();Object.defineProperty(f,"SleepInboundPolicy",{enumerable:!0,get:function(){return Yx.SleepInboundPolicy}});var Zx=op();Object.defineProperty(f,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return Zx.StripeWebhookVerificationInboundPolicy}});var Xx=o_();Object.defineProperty(f,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return Xx.SupabaseJwtInboundPolicy}});var eC=a_();Object.defineProperty(f,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return eC.UpstreamAzureAdServiceAuthInboundPolicy}});var tC=u_();Object.defineProperty(f,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return tC.UpstreamFirebaseAdminAuthInboundPolicy}});var rC=l_();Object.defineProperty(f,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return rC.UpstreamFirebaseUserAuthInboundPolicy}});var nC=p_();Object.defineProperty(f,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return nC.UpstreamGcpJwtInboundPolicy}});var iC=f_();Object.defineProperty(f,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return iC.UpstreamGcpServiceAuthInboundPolicy}});var oC=y_();Object.defineProperty(f,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return oC.ValidateJsonSchemaInbound}});var sC=__();Object.defineProperty(f,"MeteringInboundPolicy",{enumerable:!0,get:function(){return sC.MeteringInboundPolicy}});var aC=w_();Object.defineProperty(f,"LoadSubscriptionInboundPolicy",{enumerable:!0,get:function(){return aC.LoadSubscriptionInboundPolicy}});var cC=se();Object.defineProperty(f,"HttpProblems",{enumerable:!0,get:function(){return cC.HttpProblems}});var uC=mo();Object.defineProperty(f,"ProblemResponseFormatter",{enumerable:!0,get:function(){return uC.ProblemResponseFormatter}});var lC=He();Object.defineProperty(f,"ZuploRequest",{enumerable:!0,get:function(){return lC.ZuploRequest}});var dC=Ar();Object.defineProperty(f,"SystemRouteName",{enumerable:!0,get:function(){return dC.SystemRouteName}});var N_=md();Object.defineProperty(f,"LookupResult",{enumerable:!0,get:function(){return N_.LookupResult}});Object.defineProperty(f,"Router",{enumerable:!0,get:function(){return N_.Router}});var x_=Au();Object.defineProperty(f,"ContentTypes",{enumerable:!0,get:function(){return x_.ContentTypes}});Object.defineProperty(f,"serialize",{enumerable:!0,get:function(){return x_.serialize}});var pC=v_();Object.defineProperty(f,"ServiceProviderImpl",{enumerable:!0,get:function(){return pC.ServiceProviderImpl}});var C_=Wu();Object.defineProperty(f,"API_KEY",{enumerable:!0,get:function(){return C_.API_KEY}});Object.defineProperty(f,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return C_.SYSTEM_LOGGER}});var hC=Hu();Object.defineProperty(f,"httpStatuses",{enumerable:!0,get:function(){return nx(hC).default}});var fC=Le();Object.defineProperty(f,"SystemLogMap",{enumerable:!0,get:function(){return fC.SystemLogMap}});var Mi=Ya();Object.defineProperty(f,"getIdForParameterSchema",{enumerable:!0,get:function(){return Mi.getIdForParameterSchema}});Object.defineProperty(f,"getIdForRefSchema",{enumerable:!0,get:function(){return Mi.getIdForRefSchema}});Object.defineProperty(f,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Mi.getIdForRequestBodySchema}});Object.defineProperty(f,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Mi.getRawOperationDataIdentifierName}});Object.defineProperty(f,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Mi.sanitizedIdentifierName}})});var D_=g(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.BaseCryptoBeta=qn.supportedDigests=void 0;qn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var qp=class{static{s(this,"BaseCryptoBeta")}};qn.BaseCryptoBeta=qp});var U_=g(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.WorkerCryptoBeta=void 0;var $p=D_(),mC=L(),jp=class extends $p.BaseCryptoBeta{static{s(this,"WorkerCryptoBeta")}async digest(t,r){if(!$p.supportedDigests.includes(t.toLowerCase()))throw new mC.RuntimeError(`Algorithm ${t} is not supported. Try using ${$p.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};wc.WorkerCryptoBeta=jp});var k_=g(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.BaseKeyValueStore=void 0;var Vp=class{static{s(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};vc.BaseKeyValueStore=Vp});var H_=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.WorkerKeyValueStore=void 0;var M_=L(),yC=k_(),Gp=class extends yC.BaseKeyValueStore{static{s(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new M_.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new M_.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Tc.WorkerKeyValueStore=Gp});var Lt=g(dt=>{"use strict";var gC=dt&&dt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),bC=dt&&dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&gC(t,e,r)};Object.defineProperty(dt,"__esModule",{value:!0});dt.KeyValueStore=dt.CryptoBeta=void 0;bC(L_(),dt);var _C=U_();Object.defineProperty(dt,"CryptoBeta",{enumerable:!0,get:function(){return _C.WorkerCryptoBeta}});var EC=H_();Object.defineProperty(dt,"KeyValueStore",{enumerable:!0,get:function(){return EC.WorkerKeyValueStore}})});var AL={};Xi(AL,{GraphQLComplexityLimitInboundPolicy:()=>yE,GraphQLDisableIntrospectionInboundPolicy:()=>bE});module.exports=eo(AL);var Zn=yh(Lt());function B(e,t){if(!!!e)throw new Error(t)}s(B,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}s(Ee,"isObjectLike");function At(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}s(At,"invariant");var wC=/\r\n|[\n\r]/g;function $n(e,t){let r=0,n=1;for(let i of e.body.matchAll(wC)){if(typeof i.index=="number"||At(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}s($n,"getLocation");function Bp(e){return Sc(e.source,$n(e.source,e.start))}s(Bp,"printLocation");function Sc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,o=e.locationOffset.line-1,a=t.line+o,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
75
75
  `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let m=Math.floor(u/80),h=u%80,y=[];for(let v=0;v<p.length;v+=80)y.push(p.slice(v,v+80));return l+F_([[`${a} |`,y[0]],...y.slice(1,m+1).map(v=>["|",v]),["|","^".padStart(h)],["|",y[m+1]]])}return l+F_([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}s(Sc,"printSourceLocation");function F_(e){let t=e.filter(([n,i])=>i!==void 0),r=Math.max(...t.map(([n])=>n.length));return t.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
76
76
  `)}s(F_,"printPrefixedLines");function vC(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}s(vC,"toNormalizedOptions");var x=class e extends Error{static{s(this,"GraphQLError")}constructor(t,...r){var n,i,o;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=vC(r);super(t),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=q_(Array.isArray(a)?a:a?[a]:void 0);let m=q_((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(m==null||(i=m[0])===null||i===void 0?void 0:i.source),this.positions=u??m?.map(y=>y.start),this.locations=u&&c?u.map(y=>$n(c,y)):m?.map(y=>$n(y.source,y.start));let h=Ee(d?.extensions)?d?.extensions:void 0;this.extensions=(o=p??h)!==null&&o!==void 0?o:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(t+=`
77
77
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1718.0",
3
+ "version": "5.1720.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {