@zuplo/runtime 5.1761.0 → 5.1762.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
@@ -68,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new ae(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  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.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Zc,"validateComputedSignature");function qc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(qc,"parseHeader");function $c(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s($c,"secureCompare");async function Fc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Hr[i[u]];return a.join("")}s(Fc,"computeHMACSignatureAsync");var Hr=new Array(256);for(let t=0;t<Hr.length;t++)Hr[t]=t.toString(16).padStart(2,"0");function Z(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(Z,"optionValidator");var rn=s(async(t,e,n,r)=>{Z(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await ji(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),P.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");function zi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(zi,"isStripeWebhookEvent");var on=class extends ue{static{s(this,"MeteringPlugin")}};var Bc={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new E(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new E(i)}}},Vi=Bc;async function Ur(t,e,n,r){let o=n.data?.object?.subscription;if(!o)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let i=n.data?.object?.client_reference_id,a=n.data?.object?.customer_email;if(!i)throw new E("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new E("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let u=await Vi.getSubscription({logger:e.log,stripeSecretKey:r.stripeSecretKey,subscriptionId:o}),c=u.id,l=u.customer,d=u.items?.data.find(R=>R.object==="subscription_item");if(!d||!d.id)throw new E("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new E("Invalid Stripe API result. Expected subscription_item to have a plan.");let h=p.product,m=await jc({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:h,stripeSubscriptionId:c,stripeCustomerId:l,managerEmail:a,managerSub:i,context:e});if(!m)return P.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});let w="routes.oas.json";try{await zc({context:e,stripeProductId:h,stripeSubscriptionId:c,customerKey:m,productKey:w,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:l})}catch(R){return P.internalServerError(t,e,{detail:R.message})}return P.ok(t,e)}s(Ur,"onCheckoutSessionCompleted");async function jc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},h=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await h.json();if(h.status!==200){let w="Error creating API Key Consumer";throw a.log.error(w,m),new E(w)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(jc,"createConsumer");async function zc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!Le(l))throw new T("No Zuplo JWT token set.");let p=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let h="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(h,m),new E(h)}t.log.info("Successfully created/updated metering subscription.",c)}s(zc,"saveSubscription");async function Nr(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!Le(o))throw new T("No Zuplo JWT token set.");let a=n.data.object.id,u=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":e.requestId},method:"GET"});if(!u.ok){let p="Error querying for metering subscription.",h;try{h=await u.json()}catch{h={status:u.status,statusText:u.statusText}}throw e.log.error(p,h),new E(p)}let l=(await u.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return P.ok(t,e,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",h;try{h=await d.json()}catch{h={status:d.status,statusText:d.statusText}}throw e.log.error(p,h),new E(p)}return e.log.info("Successfully canceled metering subscription."),P.ok(t,e)}s(Nr,"onCustomerSubscriptionDeleted");var Mr=class extends on{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)d=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.meteringBucketRegion??"us-central1";if(!Vc(h))throw new g(`StripeMeteringPlugin - The value '${h}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!zi(m))return P.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"checkout.session.completed":return await Ur(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Nr(c,l,m,{meteringBucketId:d});default:return P.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Qo({inboundPolicies:[{handler:rn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new D({processors:[j,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Wi=new WeakMap,Gi={},sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Wi.set(e,n)}};async function Ki(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Go(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Wi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ee(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},h=Gi[n.apiKey];if(!h){let m=n.apiKey,w=t.headers.get("zm-test-id")??"";h=new C("amberflo-ingest-meter",10,async R=>{try{let I=n.url??"https://app.amberflo.io/ingest",x=await fetch(I,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Gi[m]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),t}s(Ki,"AmberfloMeteringInboundPolicy");async function an(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(an,"sha256");var Ji=new Map;async function q(t,e){let n,r=Ji.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await an(JSON.stringify({policyName:t,options:e}))}`,Ji.set(t,n)),n}s(q,"getPolicyCacheName");var Yi="key-metadata-cache-type";function Gc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Gc,"getKeyValue");async function un(t,e,n,r){if(!n.bucketName)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:P.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Gc(a,o);if(!u||u==="")return i("No key present");let c=await Wc(u),l=await q(r,o),d=new U(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Yi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},m=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(h)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),x=JSON.parse(I);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let w=await m.json(),R={isValid:!0,typeId:Yi,user:{sub:w.name,data:w.metadata}};return t.user=R.user,d.put(c,R,o.cacheTtlSeconds),t}s(un,"ApiKeyInboundPolicy");async function Wc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Wc,"hashValue");var Qi=un;var ct=require("jose");var Zr={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Zr[e.jwkUrl]||(Zr[e.jwkUrl]=(0,ct.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ct.jwtVerify)(t,Zr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ct.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),$=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(h=>P.unauthorized(t,e,{detail:h}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,n)}catch(m){let w=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Xi=s(async(t,e,n,r)=>$(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var es=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>P.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),m=d.substring(p+1),w=n.accounts.find(R=>R.username===h&&R.password===m);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Yc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Qc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Qc,"digestMessage");var Xc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Qc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ts(t,e,n,r){let o=await q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Xc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let h=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Yc.forEach(w=>m.headers.delete(w)),m.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(ts,"CachingInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new A(t,{method:n.method})},"ChangeMethodInboundPolicy");var rs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new A(t,{headers:o})},"ClearHeadersInboundPolicy");var os=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var is=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",$(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ss=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return $(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var as=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=N.instance,i=et(n.policies,o?.routeData.policies);return tr(i)(t,e)},"CompositeInboundPolicy");var us=s(async(t,e,n)=>{let r=t.user;if(!r)return P.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return P.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await el(i,o,e);if(!a)return P.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return P.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return P.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await tl(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function el(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(el,"getSubscription");async function tl(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(tl,"consumeSubscription");var cs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return P.unauthorized(t,e,{detail:"No authorization header"});let i=nl(o);if(!i)return P.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await q(r,n),u=new U(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),P.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):P.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function nl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(nl,"getToken");var ls=s(async(t,e,n,r)=>(Z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),$(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ds=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new A(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ze="__unknown__",ps=s(async(t,e,n,r)=>{let o={allow:{countries:$e(n.allow?.countries,"allow.countries",r),regionCodes:$e(n.allow?.regionCodes,"allow.regionCode",r),asns:$e(n.allow?.asns,"allow.asOrganization",r)},block:{countries:$e(n.block?.countries,"block.countries",r),regionCodes:$e(n.block?.regionCodes,"block.regionCode",r),asns:$e(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ze,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ze,u=e.incomingRequestProperties.asn?.toString()??Ze,c=o.ignoreUnknown&&i===Ze,l=o.ignoreUnknown&&a===Ze,d=o.ignoreUnknown&&u===Ze,p=o.allow.countries,h=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return qe(t,e,r,i,a,u);let w=o.block.countries,R=o.block.regionCodes,I=o.block.asns;return w.length>0&&w.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?qe(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function qe(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),P.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(qe,"blockedResponse");function $e(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s($e,"toLowerStringArray");var ms=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return qr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return qr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return gs(a[u])}else return a.length>0?gs(a[0]):qr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function gs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(gs,"generateResponse");var qr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return P.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var rl="Incoming",ol={logRequestBody:!0,logResponseBody:!0};function hs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(hs,"headersToObject");function ys(){return new Date().toISOString()}s(ys,"timestamp");var $r=new WeakMap,il={};function Rs(t,e){let n=$r.get(t);n||(n=il);let r=Object.assign({...n},e);$r.set(t,r)}s(Rs,"setMoesifContext");async function bs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(bs,"readBody");var sl={},Fr;function ws(){if(!Fr)throw new E("Invalid State - no _lastLogger");return Fr}s(ws,"getLastLogger");function al(t){let e=sl[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ws().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ws().error({status:o.status,body:await o.text()})})),e}s(al,"getDispatcher");async function Ps(t,e,n,r){Fr=e.log;let o=ys(),i=Object.assign(ol,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await bs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=al(i.applicationId),d=t.headers.get("true-client-ip"),p=$r.get(e)??{},h={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:hs(t.headers)},m=i.logResponseBody?await bs(u,e):void 0,w={time:ys(),status:u.status,headers:hs(u.headers),body:m},R={request:h,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:rl};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),t}s(Ps,"MoesifInboundPolicy");var Es=s(async(t,e,n,r)=>$(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Is=require("jose");var Br,xs=s(async(t,e,n,r)=>{if(!Br)try{Br=await(0,Is.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return $(t,e,{issuer:n.authUrl,secret:Br,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Os=Oe(Re());var cn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},jr=class extends cn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},zr=class extends cn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function ul(t,e){if(zo(t))throw new jr(e)}s(ul,"throwIfUndefinedOrNull");function lt(t,e){if(ul(t,e),!Q(t))throw new zr(e,"string")}s(lt,"throwIfNotString");var ln=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return lt(e,"redisClientUrl"),lt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){lt(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},dn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(lt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var pn=(0,Os.debug)("zuplo:policies:RateLimitInboundPolicy"),cl="strict",ll=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),dl=s(async t=>({key:`ip-${ll(t)}`}),"getIP"),pl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),ml=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),mn;function gl(t,e){let n;if(mn)return mn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new dn,mn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=ln.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return mn=n,n}s(gl,"getRedisClient");async function vs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(vs,"getCountAndUpdateExpiry");function fl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(fl,"wrapUserFunction");var hl="Retry-After",Vr=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[hl]=l.toString()),P.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:fl(n,r),user:pl,ip:dl,all:ml}[n.rateLimitBy],d=await l(t,e,r),p=d.key,h=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",R=gl(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??cl)==="async"){let _=await q(r,n),V=new re(_,{logger:S.getLogger(e)}),K=vs(x,m,R,i,e.requestId),J=await V.get(x);if(J!==void 0&&J<=Date.now()){pn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let xe=Math.round((J-Date.now())/1e3);return u(w,xe)}return e.addEventListener("responseSending",xe=>{try{let ve=xe,Pn=ve.mutableResponse;ve.mutableResponse=(async()=>{let dt=await K;if(dt.count>h){let aa=Date.now()+dt.ttlSeconds*1e3,ua=V.put(x,aa,dt.ttlSeconds).catch(to=>{throw i.error(new T("Error caching rate limit result.",{cause:to})),to});return e.waitUntil(ua),pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,dt.ttlSeconds)}return Pn})()}catch(ve){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,ve)}}),t}let F=await vs(x,m,R,i,e.requestId);return F.count>h?(pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,F.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;pn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Gr;function Ts(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ts,"headersToNameValuePairs");function yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(yl,"queryToNameValueParis");function bl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(bl,"parseIntOrUndefined");var Ss={};async function Cs(t,e,n,r){let o=new Date,i=Date.now();return Gr||(Gr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ee(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ee(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Gr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ts(t.headers),queryString:yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ts(a.headers),content:{size:bl(t.headers.get("content-length"))}}}]}}},d=Ss[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async h=>{try{let m=n.url??"https://metrics.readme.io/request",w=await fetch(m,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Ss[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Cs,"ReadmeMetricsInboundPolicy");var As=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new A(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ls=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new A(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ks=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Ds=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Hs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Ds():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ds():t},"RequestSizeLimitInboundPolicy");function Us(t,e,n){return`_${be(t+"_"+e+"_"+n)}`}s(Us,"getRawOperationDataIdentifierName");function gn(t,e,n,r){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(gn,"getIdForParameterSchema");function fn(t,e,n){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${be(n.toLowerCase())}`}s(fn,"getIdForRequestBodySchema");function Ns(t,e){return`_${be(t)}__${be(e)}`}s(Ns,"getIdForRefSchema");function be(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(be,"sanitizedIdentifierName");var Fe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Be=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=gn(n,r,o,c.name),p=N.instance.schemaValidator[d],h=p(e[c.name]),m=Wr(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Wr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ms(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=P.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",w,[r],m),ne(n.validateBody))return R}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=fn(t.route.path,e.method,o),u=N.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Wr(l),h=P.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return h}s(Ms,"handleBodyValidation");function Zs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Fe(t),i=Be(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=P.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Zs,"handleHeadersValidation");function qs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(qs,"handlePathParameterValidation");function $s(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s($s,"handleQueryParameterValidation");var Kr=s(async(t,e,n)=>{let r=$s(e,t,n);if(r!==void 0||(r=qs(e,t,n),r!==void 0)||(r=Zs(e,t,n),r!==void 0))return r;let o=await Ms(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Fs=Kr;var Bs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return P.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var js=s(async(t,e,n)=>new A(t,{body:n.body}),"SetBodyInboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new A(t,{headers:i})},"SetHeadersInboundPolicy");var Vs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Gs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new A(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ws=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var wl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wl(n.sleepInMs),t},"SleepInboundPolicy");var Js=s(async(t,e,n,r)=>{Z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await $(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof A))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?P.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ys=s(async(t,e,n,r)=>{Z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await q(r,n),i=new U(o,e),a=await i.get(r);if(!a){let u=await Rl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Rl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Y({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(Rl,"getAccessToken");var Qs="https://accounts.google.com/o/oauth2/token",Jr,Xs=s(async(t,e,n,r)=>{Z(n,r).required("serviceAccountJson","string"),Jr||(Jr=await G.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await q(r,n),a=new U(i,e),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Jr,audience:Qs,payload:o}),l=await Dt(Qs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",El=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Yr,ea=s(async(t,e,n,r)=>{if(Z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(El.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Yr||(Yr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ee(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await q(r,n),u=new U(a,e),c={uid:i,claims:o},l=await an(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Yr,audience:Pl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await ci(h,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Qr,ta=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string"),Qr||(Qr=await G.init(n.serviceAccountJson));let o=await ie({serviceAccount:Qr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var na="https://www.googleapis.com/oauth2/v4/token",Xr,ra=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Xr||(Xr=await G.init(n.serviceAccountJson));let o=await q(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new U(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Xr,audience:na,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await Dt(na,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var oa=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return P.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return P.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,h)=>{let m=le.get(h,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:R,meteringServiceUrl:I}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${I}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${R}`,"zp-rid":h.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=le.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return P.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var sa=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:P.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let h=`${n.bucketId}-${l}`,m=new re(h,{logger:S.getLogger(e)}),w=await m.get(h);if(w)d=w;else{let R=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!R.ok)return e.log.error(await R.text()),P.forbidden(t,e);d=await R.json(),m.put(h,d,15).catch(I=>{throw o.error(I),I})}}catch(h){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,h)}if((!d||!d.data||d.data.length===0)&&!i)return P.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return le.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var hn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var eo=["sha-1","sha-256","sha-384","sha-512"],yn=class{static{s(this,"BaseCryptoBeta")}};var bn=class extends yn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!eo.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${eo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var wn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Rn=class extends wn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new pt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Zc,"validateComputedSignature");function qc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(qc,"parseHeader");function $c(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s($c,"secureCompare");async function Fc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Hr[i[u]];return a.join("")}s(Fc,"computeHMACSignatureAsync");var Hr=new Array(256);for(let t=0;t<Hr.length;t++)Hr[t]=t.toString(16).padStart(2,"0");function Z(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(Z,"optionValidator");var rn=s(async(t,e,n,r)=>{Z(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await ji(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),P.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");function zi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(zi,"isStripeWebhookEvent");var on=class extends ue{static{s(this,"MeteringPlugin")}};var Bc={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new E(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new E(i)}}},Vi=Bc;async function Ur(t,e,n,r){let o=n.data?.object?.subscription;if(!o)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let i=n.data?.object?.client_reference_id,a=n.data?.object?.customer_email;if(!i)throw new E("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new E("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let u=await Vi.getSubscription({logger:e.log,stripeSecretKey:r.stripeSecretKey,subscriptionId:o}),c=u.id,l=u.customer,d=u.items?.data.find(R=>R.object==="subscription_item");if(!d||!d.id)throw new E("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new E("Invalid Stripe API result. Expected subscription_item to have a plan.");let h=p.product,m=await jc({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:h,stripeSubscriptionId:c,stripeCustomerId:l,managerEmail:a,managerSub:i,context:e});if(!m)return P.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});let w="routes.oas.json";try{await zc({context:e,stripeProductId:h,stripeSubscriptionId:c,customerKey:m,productKey:w,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:l})}catch(R){return P.internalServerError(t,e,{detail:R.message})}return P.ok(t,e)}s(Ur,"onCheckoutSessionCompleted");async function jc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},h=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await h.json();if(h.status!==200){let w="Error creating API Key Consumer";throw a.log.error(w,m),new E(w)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(jc,"createConsumer");async function zc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!Le(l))throw new T("No Zuplo JWT token set.");let p=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let h="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(h,m),new E(h)}t.log.info("Successfully created/updated metering subscription.",c)}s(zc,"saveSubscription");async function Nr(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!Le(o))throw new T("No Zuplo JWT token set.");let a=n.data.object.id,u=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions?subscriptionExternalId=${a}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":e.requestId},method:"GET"});if(!u.ok){let p="Error querying for metering subscription.",h;try{h=await u.json()}catch{h={status:u.status,statusText:u.statusText}}throw e.log.error(p,h),new E(p)}let l=(await u.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return P.ok(t,e,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",h;try{h=await d.json()}catch{h={status:d.status,statusText:d.statusText}}throw e.log.error(p,h),new E(p)}return e.log.info("Successfully canceled metering subscription."),P.ok(t,e)}s(Nr,"onCustomerSubscriptionDeleted");var Mr=class extends on{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)d=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.meteringBucketRegion??"us-central1";if(!Vc(h))throw new g(`StripeMeteringPlugin - The value '${h}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!zi(m))return P.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"checkout.session.completed":return await Ur(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Nr(c,l,m,{meteringBucketId:d});default:return P.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Qo({inboundPolicies:[{handler:rn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new D({processors:[j,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Wi=new WeakMap,Gi={},sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Wi.set(e,n)}};async function Ki(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Go(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Wi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ee(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},h=Gi[n.apiKey];if(!h){let m=n.apiKey,w=t.headers.get("zm-test-id")??"";h=new C("amberflo-ingest-meter",10,async R=>{try{let I=n.url??"https://app.amberflo.io/ingest",x=await fetch(I,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Gi[m]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),t}s(Ki,"AmberfloMeteringInboundPolicy");async function an(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(an,"sha256");var Ji=new Map;async function q(t,e){let n,r=Ji.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await an(JSON.stringify({policyName:t,options:e}))}`,Ji.set(t,n)),n}s(q,"getPolicyCacheName");var Yi="key-metadata-cache-type";function Gc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Gc,"getKeyValue");async function un(t,e,n,r){if(!n.bucketName)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:P.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Gc(a,o);if(!u||u==="")return i("No key present");let c=await Wc(u),l=await q(r,o),d=new U(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Yi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},m=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(h)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),x=JSON.parse(I);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let w=await m.json(),R={isValid:!0,typeId:Yi,user:{sub:w.name,data:w.metadata}};return t.user=R.user,d.put(c,R,o.cacheTtlSeconds),t}s(un,"ApiKeyInboundPolicy");async function Wc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Wc,"hashValue");var Qi=un;var ct=require("jose");var Zr={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Zr[e.jwkUrl]||(Zr[e.jwkUrl]=(0,ct.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ct.jwtVerify)(t,Zr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ct.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),$=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(h=>P.unauthorized(t,e,{detail:h}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,n)}catch(m){let w=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Xi=s(async(t,e,n,r)=>$(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var es=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>P.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),m=d.substring(p+1),w=n.accounts.find(R=>R.username===h&&R.password===m);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Yc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Qc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Qc,"digestMessage");var Xc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Qc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ts(t,e,n,r){let o=await q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Xc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let h=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Yc.forEach(w=>m.headers.delete(w)),m.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(ts,"CachingInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new A(t,{method:n.method})},"ChangeMethodInboundPolicy");var rs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new A(t,{headers:o})},"ClearHeadersInboundPolicy");var os=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var is=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",$(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ss=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return $(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var as=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=N.instance,i=et(n.policies,o?.routeData.policies);return tr(i)(t,e)},"CompositeInboundPolicy");var us=s(async(t,e,n)=>{let r=t.user;if(!r)return P.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return P.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await el(i,o,e);if(!a)return P.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return P.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return P.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await tl(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function el(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(el,"getSubscription");async function tl(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(tl,"consumeSubscription");var cs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return P.unauthorized(t,e,{detail:"No authorization header"});let i=nl(o);if(!i)return P.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await q(r,n),u=new U(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),P.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):P.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function nl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(nl,"getToken");var ls=s(async(t,e,n,r)=>(Z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),$(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ds=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new A(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ze="__unknown__",ps=s(async(t,e,n,r)=>{let o={allow:{countries:$e(n.allow?.countries,"allow.countries",r),regionCodes:$e(n.allow?.regionCodes,"allow.regionCode",r),asns:$e(n.allow?.asns,"allow.asOrganization",r)},block:{countries:$e(n.block?.countries,"block.countries",r),regionCodes:$e(n.block?.regionCodes,"block.regionCode",r),asns:$e(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ze,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ze,u=e.incomingRequestProperties.asn?.toString()??Ze,c=o.ignoreUnknown&&i===Ze,l=o.ignoreUnknown&&a===Ze,d=o.ignoreUnknown&&u===Ze,p=o.allow.countries,h=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return qe(t,e,r,i,a,u);let w=o.block.countries,R=o.block.regionCodes,I=o.block.asns;return w.length>0&&w.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?qe(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function qe(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),P.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(qe,"blockedResponse");function $e(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s($e,"toLowerStringArray");var ms=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return qr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return qr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return gs(a[u])}else return a.length>0?gs(a[0]):qr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function gs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(gs,"generateResponse");var qr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return P.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var rl="Incoming",ol={logRequestBody:!0,logResponseBody:!0};function hs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(hs,"headersToObject");function ys(){return new Date().toISOString()}s(ys,"timestamp");var $r=new WeakMap,il={};function Rs(t,e){let n=$r.get(t);n||(n=il);let r=Object.assign({...n},e);$r.set(t,r)}s(Rs,"setMoesifContext");async function bs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(bs,"readBody");var sl={},Fr;function ws(){if(!Fr)throw new E("Invalid State - no _lastLogger");return Fr}s(ws,"getLastLogger");function al(t){let e=sl[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ws().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ws().error({status:o.status,body:await o.text()})})),e}s(al,"getDispatcher");async function Ps(t,e,n,r){Fr=e.log;let o=ys(),i=Object.assign(ol,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await bs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=al(i.applicationId),d=t.headers.get("true-client-ip"),p=$r.get(e)??{},h={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:hs(t.headers)},m=i.logResponseBody?await bs(u,e):void 0,w={time:ys(),status:u.status,headers:hs(u.headers),body:m},R={request:h,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:rl};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),t}s(Ps,"MoesifInboundPolicy");var Es=s(async(t,e,n,r)=>$(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Is=require("jose");var Br,xs=s(async(t,e,n,r)=>{if(!Br)try{Br=await(0,Is.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return $(t,e,{issuer:n.authUrl,secret:Br,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Os=Oe(Re());var cn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},jr=class extends cn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},zr=class extends cn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function ul(t,e){if(zo(t))throw new jr(e)}s(ul,"throwIfUndefinedOrNull");function lt(t,e){if(ul(t,e),!Q(t))throw new zr(e,"string")}s(lt,"throwIfNotString");var ln=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return lt(e,"redisClientUrl"),lt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){lt(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},dn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(lt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var pn=(0,Os.debug)("zuplo:policies:RateLimitInboundPolicy"),cl="strict",ll=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),dl=s(async t=>({key:`ip-${ll(t)}`}),"getIP"),pl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),ml=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),mn;function gl(t,e){let n;if(mn)return mn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new dn,mn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=ln.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return mn=n,n}s(gl,"getRedisClient");async function vs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(vs,"getCountAndUpdateExpiry");function fl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(fl,"wrapUserFunction");var hl="Retry-After",Vr=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[hl]=l.toString()),P.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:fl(n,r),user:pl,ip:dl,all:ml}[n.rateLimitBy],d=await l(t,e,r),p=d.key,h=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",R=gl(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??cl)==="async"){let _=await q(r,n),V=new re(_,{logger:S.getLogger(e)}),K=vs(x,m,R,i,e.requestId),J=await V.get(x);if(J!==void 0&&J<=Date.now()){pn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let xe=Math.round((J-Date.now())/1e3);return u(w,xe)}return e.addEventListener("responseSending",xe=>{try{let ve=xe,Pn=ve.mutableResponse;ve.mutableResponse=(async()=>{let dt=await K;if(dt.count>h){let aa=Date.now()+dt.ttlSeconds*1e3,ua=V.put(x,aa,dt.ttlSeconds).catch(to=>{throw i.error(new T("Error caching rate limit result.",{cause:to})),to});return e.waitUntil(ua),pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,dt.ttlSeconds)}return Pn})()}catch(ve){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,ve)}}),t}let F=await vs(x,m,R,i,e.requestId);return F.count>h?(pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,F.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;pn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Gr;function Ts(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ts,"headersToNameValuePairs");function yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(yl,"queryToNameValueParis");function bl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(bl,"parseIntOrUndefined");var Ss={};async function Cs(t,e,n,r){let o=new Date,i=Date.now();return Gr||(Gr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ee(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ee(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Gr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ts(t.headers),queryString:yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ts(a.headers),content:{size:bl(t.headers.get("content-length"))}}}]}}},d=Ss[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async h=>{try{let m=n.url??"https://metrics.readme.io/request",w=await fetch(m,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Ss[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Cs,"ReadmeMetricsInboundPolicy");var As=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new A(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ls=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new A(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ks=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Ds=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Hs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Ds():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ds():t},"RequestSizeLimitInboundPolicy");function Us(t,e,n){return`_${be(t+"_"+e+"_"+n)}`}s(Us,"getRawOperationDataIdentifierName");function gn(t,e,n,r){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(gn,"getIdForParameterSchema");function fn(t,e,n){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${be(n.toLowerCase())}`}s(fn,"getIdForRequestBodySchema");function Ns(t,e){return`_${be(t)}__${be(e)}`}s(Ns,"getIdForRefSchema");function be(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(be,"sanitizedIdentifierName");var Fe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Be=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=gn(n,r,o,c.name),p=N.instance.schemaValidator[d],h=p(e[c.name]),m=Wr(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Wr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ms(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=P.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",w,[r],m),ne(n.validateBody))return R}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=fn(t.route.path,e.method,o),u=N.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Wr(l),h=P.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return h}s(Ms,"handleBodyValidation");function Zs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Fe(t),i=Be(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=P.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Zs,"handleHeadersValidation");function qs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(qs,"handlePathParameterValidation");function $s(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s($s,"handleQueryParameterValidation");var Kr=s(async(t,e,n)=>{let r=$s(e,t,n);if(r!==void 0||(r=qs(e,t,n),r!==void 0)||(r=Zs(e,t,n),r!==void 0))return r;let o=await Ms(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Fs=Kr;var Bs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return P.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var js=s(async(t,e,n)=>new A(t,{body:n.body}),"SetBodyInboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new A(t,{headers:i})},"SetHeadersInboundPolicy");var Vs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Gs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new A(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ws=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var wl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wl(n.sleepInMs),t},"SleepInboundPolicy");var Js=s(async(t,e,n,r)=>{Z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await $(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof A))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?P.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ys=s(async(t,e,n,r)=>{Z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await q(r,n),i=new U(o,e),a=await i.get(r);if(!a){let u=await Rl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Rl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Y({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(Rl,"getAccessToken");var Qs="https://accounts.google.com/o/oauth2/token",Jr,Xs=s(async(t,e,n,r)=>{Z(n,r).required("serviceAccountJson","string"),Jr||(Jr=await G.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await q(r,n),a=new U(i,e),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Jr,audience:Qs,payload:o}),l=await Dt(Qs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",El=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Yr,ea=s(async(t,e,n,r)=>{if(Z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(El.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Yr||(Yr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ee(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await q(r,n),u=new U(a,e),c={uid:i,claims:o},l=await an(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Yr,audience:Pl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await ci(h,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Qr,ta=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string"),Qr||(Qr=await G.init(n.serviceAccountJson));let o=await ie({serviceAccount:Qr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var na="https://www.googleapis.com/oauth2/v4/token",Xr,ra=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Xr||(Xr=await G.init(n.serviceAccountJson));let o=await q(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new U(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Xr,audience:na,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await Dt(na,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var oa=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return P.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return P.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,h)=>{let m=le.get(h,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:R,meteringServiceUrl:I}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${I}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${R}`,"zp-rid":h.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=le.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return P.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var sa=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:P.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let h=`${n.bucketId}-${l}`,m=new re(h,{logger:S.getLogger(e)}),w=await m.get(h);if(w)d=w;else{let R=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!R.ok)return e.log.error(await R.text()),P.forbidden(t,e);d=await R.json(),m.put(h,d,15).catch(I=>{throw o.error(I),I})}}catch(h){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,h)}if((!d||!d.data||d.data.length===0)&&!i)return P.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return le.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var hn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var eo=["sha-1","sha-256","sha-384","sha-512"],yn=class{static{s(this,"BaseCryptoBeta")}};var bn=class extends yn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!eo.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${eo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var wn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Rn=class extends wn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new pt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
72
72
  /*! For license information please see index.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1761.0",
3
+ "version": "5.1762.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {