@zuplo/runtime 6.35.14 → 6.38.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.
Files changed (2) hide show
  1. package/out/esm/index.js +1 -1
  2. package/package.json +1 -1
package/out/esm/index.js CHANGED
@@ -77,7 +77,7 @@ Signature verification is impossible without access to the original signed mater
77
77
  `+d}):new Me(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
78
78
  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.
79
79
  `+l+`
80
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(gl,"validateComputedSignature");function fl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(fl,"parseHeader");function hl(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(hl,"secureCompare");async function yl(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Dr[s[u]];return a.join("")}i(yl,"computeHMACSignatureAsync");var Dr=new Array(256);for(let n=0;n<Dr.length;n++)Dr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await la(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function da(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(da,"isStripeWebhookEvent");var bl={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new k(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new k(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new k(s)}return r},"getUpcomingInvoice")},_n=bl;var Mr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",pa="My API Key";async function ma({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,Mr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ma,"createConsumer");async function ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,Mr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(ga,"createConsumerInvite");async function fa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=f.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,Mr);r.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(fa,"deleteConsumer");async function ha({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!gt(p))throw new K("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(ha,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Pt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Ye="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Nn(n){return n.replaceAll("_","-")}i(Nn,"stripeStatusToMeteringStatus");function at(n){return new Date(n*1e3).toISOString()}i(at,"unixTimestampToISOString");async function Ur(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ma({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await _n.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ga({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Nn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:at(t.data.object.trial_end),trialStartDate:at(t.data.object.trial_start)}),await ha({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await fa({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Ye})}i(Ur,"onCustomerSubscriptionCreated");async function qr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Pe})}return E.ok(n,e,{title:Ye})}i(qr,"onCustomerSubscriptionDeleted");async function Zr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=Nn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=at(t.data.object.trial_end)),await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await _n.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?at(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?at(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Pe})}i(Zr,"onCustomerSubscriptionUpdated");var ya=class extends cn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(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(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!wl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!da(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Ur(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Zr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qr(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe})}},"stripeWebhookHandler"),s=Os({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:r,gateway:o}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function wl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(wl,"isMetricsRegion");var wa=new WeakMap,ba={},Hr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){wa.set(e,t)}};async function Rl(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=Ge(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=wa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=ba[t.apiKey];if(!h){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await Z.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${A.message}`),A}}),ba[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Rl,"AmberfloMeteringInboundPolicy");async function ut(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(ut,"sha256");var Ra=new Map;async function se(n,e,t){let o,r=`${n}-${e}`,s=Ra.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await ut(JSON.stringify({policyName:n,options:t}))}`,Ra.set(n,o)),o}i(se,"getPolicyCacheName");var Pa="key-metadata-cache-type";function Pl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Pl,"getKeyValue");async function $r(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(N=>r.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Pl(a,r);if(!u||u==="")return s("No key present");let c=await Il(u),l=await se(o,void 0,r),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Pa&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(h)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:Pa,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,r.cacheTtlSeconds),n}i($r,"ApiKeyInboundPolicy");async function Il(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Il,"hashValue");var El=$r;var Ia=Symbol("aserto-authz-resource-context"),Fr=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){re.set(e,Ia,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let o=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let r=re.get(t,Ia),s;r?.policyInstance?s=r.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Ze(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:r?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:r?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:r?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await Z.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?o(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),o("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as Tl,jwtVerify as xa}from"jose";import{createLocalJWKSet as xl}from"jose";var jr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof zr&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=xl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Br("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new It("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new It("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ea(n,e,t){let o=new jr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(Ea,"createRemoteJWKSet");var It=class extends k{static{i(this,"JWKSError")}},zr=class extends It{static{i(this,"JWKSNoMatchingKey")}},Br=class extends It{static{i(this,"JWKSTimeout")}};var Dn={},vl=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Dn[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await se(n,void 0,o),u=new ie(a,e);Dn[o.jwkUrl]=Ea(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else Dn[o.jwkUrl]=Tl(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await xa(t,Dn[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),Cl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await xa(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=t.authHeader??"Authorization",s=n.headers.get(r),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?vl(o,e):Cl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",h=d[p];return h?(n.user={sub:h,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ol=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var Mn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Gr=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Mn(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var Sl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===h&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Un(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Un,"extractDateElements");function Ta(n,e){return new Date(n,e+1,0).getDate()}i(Ta,"getDaysInMonth");function Vr(n,e){return n<=e?e-n:6-n+e+1}i(Vr,"getDaysBetweenWeekdays");var qn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Ta(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Vr(d,p):Vr(p,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Un(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Un(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=Un(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Al={min:0,max:59},kl={min:0,max:59},Ll={min:0,max:23},_l={min:1,max:31},Nl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Dl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Ml={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ct(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{ct(d,e).forEach(h=>t.add(h))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ct,"parseElement");function Wr(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Ml[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new qn({seconds:ct(t,Al),minutes:ct(o,kl),hours:ct(r,Ll),days:ct(s,_l),months:new Set(Array.from(ct(a,Nl)).map(c=>c-1)),weekdays:new Set(Array.from(ct(u,Dl)).map(c=>c%7))})}i(Wr,"parseCronExpression");var Jr=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Wr(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Wr(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Ul=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ql(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ql,"digestMessage");var Zl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await ql(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Hl(n,e,t,o){g("policy.inbound.caching");let r=await se(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Zl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ul.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(Hl,"CachingInboundPolicy");var $l=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new ne(n,{method:t.method})},"ChangeMethodInboundPolicy");var Fl=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new ne(n,{headers:r})},"ClearHeadersInboundPolicy");var jl=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var zl=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Bl=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Zn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Kr=class extends Zn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Qr=class extends Zn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Gl(n,e){if(Rs(n))throw new Kr(e)}i(Gl,"throwIfUndefinedOrNull");function va(n,e){if(Gl(n,e),!xe(n))throw new Qr(e,"string")}i(va,"throwIfNotString");var Yr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Vl=200,Xr=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:o,requestId:r}){va(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Vl);let a,u=new Headers({"content-type":"application/json"});_e(u,r);try{a=await Z.fetch(`${this.clientUrl}${e}`,{method:o,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await ut(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await ut(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Et;function Xe(n,e){if(Et)return Et;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Et=new Yr,Et;let{redisURL:t,authApiJWT:o}=f.instance;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Et=new Xr(t),Et}i(Xe,"getRateLimitClient");var Wl=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function xt(n,e){return{function:Yl(e,"RateLimitInboundPolicy",n),user:Kl,ip:Jl,all:Ql}[e.rateLimitBy??"ip"]}i(xt,"getRateLimitByFunctions");var Jl=i(async n=>({key:`ip-${Wl(n)}`}),"getIP"),Kl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ql=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Yl(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(Yl,"wrapUserFunction");var Tt="Retry-After";var Ca=ye("zuplo:policies:ComplexRateLimitInboundPolicy"),ei=Symbol("complex-rate-limit-counters"),ti=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=re.get(e,ei)??{};Object.assign(o,t),re.set(e,ei,t)}static getIncrements(e){return re.get(e,ei)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Xe(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Tt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await xt(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:h,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){r.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:h,limit:N})),v=await s.multiCount(y,t.requestId);return Xl(v,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Xl(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Xl,"findOverLimits");var ed=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=ge.instance,s=Ft(t.policies,r?.routeData.policies);return jo(s)(n,e)},"CompositeInboundPolicy");var td=i(async(n,e,t,o,r)=>{if(g("policy.outbound.composite"),!o.policies||o.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=ge.instance,a=jt(o.policies,s?.routeData.policies);return zo(a)(n,e,t)},"CompositeOutboundPolicy");var nd=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return E.unauthorized(n,e,{detail:"No authorization header"});let s=od(r);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(o,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function od(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(od,"getToken");var rd=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var id=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ne(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var vt="__unknown__",sd=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Ot(t.allow?.countries,"allow.countries",o),regionCodes:Ot(t.allow?.regionCodes,"allow.regionCode",o),asns:Ot(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Ot(t.block?.countries,"block.countries",o),regionCodes:Ot(t.block?.regionCodes,"block.regionCode",o),asns:Ot(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??vt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??vt,u=e.incomingRequestProperties.asn?.toString()??vt,c=r.ignoreUnknown&&s===vt,l=r.ignoreUnknown&&a===vt,d=r.ignoreUnknown&&u===vt,p=r.allow.countries,h=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ct(n,e,o,s,a,u);let v=r.block.countries,R=r.block.regionCodes,A=r.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ct(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function Ct(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(Ct,"blockedResponse");function Ot(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ot,"toLowerStringArray");var ad=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var ud=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return ni(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return ni(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[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=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Oa(a[u])}else return a.length>0?Oa(a[0]):ni(o,n,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 Oa(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Oa,"generateResponse");var ni=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return E.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var cd="Incoming",ld={logRequestBody:!0,logResponseBody:!0};function Sa(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(Sa,"headersToObject");function Aa(){return new Date().toISOString()}i(Aa,"timestamp");var oi=new WeakMap,dd={};function pd(n,e){let t=oi.get(n);t||(t=dd);let o=Object.assign({...t},e);oi.set(n,o)}i(pd,"setMoesifContext");async function ka(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(ka,"readBody");var md={},ri;function La(){if(!ri)throw new k("Invalid State - no _lastLogger");return ri}i(La,"getLastLogger");function gd(n){let e=md[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);La().debug("posting",o);let r=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||La().error({status:r.status,body:await r.text()})})),e}i(gd,"getDispatcher");async function fd(n,e,t,o){g("policy.inbound.moesif-analytics"),ri=e.log;let r=Aa(),s=Object.assign(ld,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await ka(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=gd(s.applicationId),d=n.headers.get("true-client-ip"),p=oi.get(e)??{},h={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Sa(n.headers)},y=s.logResponseBody?await ka(u,e):void 0,v={time:Aa(),status:u.status,headers:Sa(u.headers),body:y},R={request:h,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:cd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(fd,"MoesifInboundPolicy");async function _a(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(_a,"loadSubscription");async function Na(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Na,"consumeSubcriptionQuotas");var hd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Hn(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Hn,"validateMeters");function Da(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=rt(n),o=[];for(let r of t)hd.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Da,"parseAllowedSubscriptionStatuses");function Ma(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(Ma,"compareMeters");var ii=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return re.get(e,Dt)}static setMeters(e,t){Hn(t,"setMeters");let o=re.get(e,Mt)??{};Object.assign(o,t),re.set(e,Mt,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=Ge(this.options.meterOnStatusCodes),s=re.get(t,Mt),a={...this.options.meters,...s};Hn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Da(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=re.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=re.get(N,Mt),H={...this.options.meters,...z};if(Hn(H,this.policyName),r.includes(R.status)&&S&&H){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify(H)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:q}=Ma(S.meters,H);if(q&&Object.keys(q).length>0){let V=Object.keys(q);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Na(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await _a(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),re.set(t,Dt,p));let h=re.get(t,Dt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(h.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(h.meters[R].available<=0&&!o)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};async function $n(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await be({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i($n,"getClientCredentialsAccessToken");var St=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},Fn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new m("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new St("unknown",`Unknown error. Status: ${c.status}`):new St(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var Ua="X-OpenFGA-Client-Method",qa="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Fn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Xt(o,Ua,"BatchCheck"),Xt(o,qa,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof St)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,Ua,"ListRelations"),Xt(c,qa,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Za=Symbol("openfga-authz-context-data"),At=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];re.set(e,Za,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=re.get(t,Za);if(!r||r.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new K(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await $n({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ha=["us1","eu1","au1"],si=class extends At{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ha.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ha.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var yd=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var ai=class extends At{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as bd}from"jose";var ui,wd=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ui)try{ui=await bd(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:ui,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var ci="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",$a="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var li=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=Rd(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Pd(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Xe(this.policyName,r),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),o&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{o&&(R+=`${A} - allowed: ${N} value: ${h.meters[A]??0}
80
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(gl,"validateComputedSignature");function fl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(fl,"parseHeader");function hl(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(hl,"secureCompare");async function yl(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Dr[s[u]];return a.join("")}i(yl,"computeHMACSignatureAsync");var Dr=new Array(256);for(let n=0;n<Dr.length;n++)Dr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await la(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function da(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(da,"isStripeWebhookEvent");var bl={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new k(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new k(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new k(s)}return r},"getUpcomingInvoice")},_n=bl;var Mr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",pa="My API Key";async function ma({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,Mr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ma,"createConsumer");async function ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,Mr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(ga,"createConsumerInvite");async function fa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=f.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,Mr);r.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(fa,"deleteConsumer");async function ha({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!gt(p))throw new K("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(ha,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Pt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Ye="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Nn(n){return n.replaceAll("_","-")}i(Nn,"stripeStatusToMeteringStatus");function at(n){return new Date(n*1e3).toISOString()}i(at,"unixTimestampToISOString");async function Ur(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ma({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await _n.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ga({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Nn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:at(t.data.object.trial_end),trialStartDate:at(t.data.object.trial_start)}),await ha({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await fa({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Ye})}i(Ur,"onCustomerSubscriptionCreated");async function qr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Pe})}return E.ok(n,e,{title:Ye})}i(qr,"onCustomerSubscriptionDeleted");async function Zr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=Nn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=at(t.data.object.trial_end)),await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await _n.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?at(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?at(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Pe})}i(Zr,"onCustomerSubscriptionUpdated");var ya=class extends cn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(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(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!wl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!da(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Ur(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Zr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qr(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe})}},"stripeWebhookHandler"),s=Os({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:r,gateway:o}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function wl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(wl,"isMetricsRegion");var wa=new WeakMap,ba={},Hr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){wa.set(e,t)}};async function Rl(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=Ge(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=wa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=ba[t.apiKey];if(!h){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await Z.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${A.message}`),A}}),ba[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Rl,"AmberfloMeteringInboundPolicy");async function ut(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(ut,"sha256");var Ra=new Map;async function se(n,e,t){let o,r=`${n}-${e}`,s=Ra.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await ut(JSON.stringify({policyName:n,options:t}))}`,Ra.set(n,o)),o}i(se,"getPolicyCacheName");var Pa="key-metadata-cache-type";function Pl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Pl,"getKeyValue");async function $r(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(N=>r.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Pl(a,r);if(!u||u==="")return s("No key present");let c=await Il(u),l=await se(o,void 0,r),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Pa&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(h)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:Pa,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,r.cacheTtlSeconds),n}i($r,"ApiKeyInboundPolicy");async function Il(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Il,"hashValue");var El=$r;var Ia=Symbol("aserto-authz-resource-context"),Fr=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){re.set(e,Ia,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let o=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let r=re.get(t,Ia),s;r?.policyInstance?s=r.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Ze(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:r?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:r?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:r?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await Z.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?o(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),o("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as Tl,jwtVerify as xa}from"jose";import{createLocalJWKSet as xl}from"jose";var jr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof zr&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=xl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Br("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new It("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new It("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ea(n,e,t){let o=new jr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(Ea,"createRemoteJWKSet");var It=class extends k{static{i(this,"JWKSError")}},zr=class extends It{static{i(this,"JWKSNoMatchingKey")}},Br=class extends It{static{i(this,"JWKSTimeout")}};var Dn={},vl=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Dn[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await se(n,void 0,o),u=new ie(a,e);Dn[o.jwkUrl]=Ea(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else Dn[o.jwkUrl]=Tl(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await xa(t,Dn[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),Cl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await xa(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=t.authHeader??"Authorization",s=n.headers.get(r),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?vl(o,e):Cl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",h=d[p];return h?(n.user={sub:h,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ol=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var Mn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Gr=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Mn(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var Sl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===h&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Un(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Un,"extractDateElements");function Ta(n,e){return new Date(n,e+1,0).getDate()}i(Ta,"getDaysInMonth");function Vr(n,e){return n<=e?e-n:6-n+e+1}i(Vr,"getDaysBetweenWeekdays");var qn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Ta(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Vr(d,p):Vr(p,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Un(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Un(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=Un(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Al={min:0,max:59},kl={min:0,max:59},Ll={min:0,max:23},_l={min:1,max:31},Nl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Dl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Ml={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ct(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{ct(d,e).forEach(h=>t.add(h))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ct,"parseElement");function Wr(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Ml[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new qn({seconds:ct(t,Al),minutes:ct(o,kl),hours:ct(r,Ll),days:ct(s,_l),months:new Set(Array.from(ct(a,Nl)).map(c=>c-1)),weekdays:new Set(Array.from(ct(u,Dl)).map(c=>c%7))})}i(Wr,"parseCronExpression");var Jr=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Wr(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Wr(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Ul=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ql(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ql,"digestMessage");var Zl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await ql(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Hl(n,e,t,o){g("policy.inbound.caching");let r=await se(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Zl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ul.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(Hl,"CachingInboundPolicy");var $l=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new ne(n,{method:t.method})},"ChangeMethodInboundPolicy");var Fl=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new ne(n,{headers:r})},"ClearHeadersInboundPolicy");var jl=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var zl=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Bl=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Zn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Kr=class extends Zn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Qr=class extends Zn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Gl(n,e){if(Rs(n))throw new Kr(e)}i(Gl,"throwIfUndefinedOrNull");function va(n,e){if(Gl(n,e),!xe(n))throw new Qr(e,"string")}i(va,"throwIfNotString");var Yr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Vl=500,Xr=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:o,requestId:r}){va(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Vl);let a,u=new Headers({"content-type":"application/json"});_e(u,r);try{a=await Z.fetch(`${this.clientUrl}${e}`,{method:o,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await ut(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await ut(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Et;function Xe(n,e){if(Et)return Et;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Et=new Yr,Et;let{redisURL:t,authApiJWT:o}=f.instance;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Et=new Xr(t),Et}i(Xe,"getRateLimitClient");var Wl=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function xt(n,e){return{function:Yl(e,"RateLimitInboundPolicy",n),user:Kl,ip:Jl,all:Ql}[e.rateLimitBy??"ip"]}i(xt,"getRateLimitByFunctions");var Jl=i(async n=>({key:`ip-${Wl(n)}`}),"getIP"),Kl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ql=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Yl(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(Yl,"wrapUserFunction");var Tt="Retry-After";var Ca=ye("zuplo:policies:ComplexRateLimitInboundPolicy"),ei=Symbol("complex-rate-limit-counters"),ti=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=re.get(e,ei)??{};Object.assign(o,t),re.set(e,ei,t)}static getIncrements(e){return re.get(e,ei)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Xe(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Tt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await xt(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:h,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){r.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:h,limit:N})),v=await s.multiCount(y,t.requestId);return Xl(v,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Xl(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Xl,"findOverLimits");var ed=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=ge.instance,s=Ft(t.policies,r?.routeData.policies);return jo(s)(n,e)},"CompositeInboundPolicy");var td=i(async(n,e,t,o,r)=>{if(g("policy.outbound.composite"),!o.policies||o.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=ge.instance,a=jt(o.policies,s?.routeData.policies);return zo(a)(n,e,t)},"CompositeOutboundPolicy");var nd=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return E.unauthorized(n,e,{detail:"No authorization header"});let s=od(r);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(o,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function od(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(od,"getToken");var rd=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var id=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ne(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var vt="__unknown__",sd=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Ot(t.allow?.countries,"allow.countries",o),regionCodes:Ot(t.allow?.regionCodes,"allow.regionCode",o),asns:Ot(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Ot(t.block?.countries,"block.countries",o),regionCodes:Ot(t.block?.regionCodes,"block.regionCode",o),asns:Ot(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??vt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??vt,u=e.incomingRequestProperties.asn?.toString()??vt,c=r.ignoreUnknown&&s===vt,l=r.ignoreUnknown&&a===vt,d=r.ignoreUnknown&&u===vt,p=r.allow.countries,h=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ct(n,e,o,s,a,u);let v=r.block.countries,R=r.block.regionCodes,A=r.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ct(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function Ct(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(Ct,"blockedResponse");function Ot(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ot,"toLowerStringArray");var ad=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var ud=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return ni(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return ni(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[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=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Oa(a[u])}else return a.length>0?Oa(a[0]):ni(o,n,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 Oa(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Oa,"generateResponse");var ni=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return E.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var cd="Incoming",ld={logRequestBody:!0,logResponseBody:!0};function Sa(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(Sa,"headersToObject");function Aa(){return new Date().toISOString()}i(Aa,"timestamp");var oi=new WeakMap,dd={};function pd(n,e){let t=oi.get(n);t||(t=dd);let o=Object.assign({...t},e);oi.set(n,o)}i(pd,"setMoesifContext");async function ka(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(ka,"readBody");var md={},ri;function La(){if(!ri)throw new k("Invalid State - no _lastLogger");return ri}i(La,"getLastLogger");function gd(n){let e=md[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);La().debug("posting",o);let r=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||La().error({status:r.status,body:await r.text()})})),e}i(gd,"getDispatcher");async function fd(n,e,t,o){g("policy.inbound.moesif-analytics"),ri=e.log;let r=Aa(),s=Object.assign(ld,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await ka(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=gd(s.applicationId),d=n.headers.get("true-client-ip"),p=oi.get(e)??{},h={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Sa(n.headers)},y=s.logResponseBody?await ka(u,e):void 0,v={time:Aa(),status:u.status,headers:Sa(u.headers),body:y},R={request:h,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:cd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(fd,"MoesifInboundPolicy");async function _a(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(_a,"loadSubscription");async function Na(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Na,"consumeSubcriptionQuotas");var hd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Hn(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Hn,"validateMeters");function Da(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=rt(n),o=[];for(let r of t)hd.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Da,"parseAllowedSubscriptionStatuses");function Ma(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(Ma,"compareMeters");var ii=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return re.get(e,Dt)}static setMeters(e,t){Hn(t,"setMeters");let o=re.get(e,Mt)??{};Object.assign(o,t),re.set(e,Mt,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=Ge(this.options.meterOnStatusCodes),s=re.get(t,Mt),a={...this.options.meters,...s};Hn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Da(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=re.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=re.get(N,Mt),H={...this.options.meters,...z};if(Hn(H,this.policyName),r.includes(R.status)&&S&&H){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify(H)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:q}=Ma(S.meters,H);if(q&&Object.keys(q).length>0){let V=Object.keys(q);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Na(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await _a(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),re.set(t,Dt,p));let h=re.get(t,Dt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(h.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(h.meters[R].available<=0&&!o)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};async function $n(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await be({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i($n,"getClientCredentialsAccessToken");var St=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},Fn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new m("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new St("unknown",`Unknown error. Status: ${c.status}`):new St(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var Ua="X-OpenFGA-Client-Method",qa="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Fn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Xt(o,Ua,"BatchCheck"),Xt(o,qa,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof St)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,Ua,"ListRelations"),Xt(c,qa,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Za=Symbol("openfga-authz-context-data"),At=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];re.set(e,Za,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=re.get(t,Za);if(!r||r.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new K(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await $n({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ha=["us1","eu1","au1"],si=class extends At{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ha.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ha.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var yd=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var ai=class extends At{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as bd}from"jose";var ui,wd=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ui)try{ui=await bd(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:ui,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var ci="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",$a="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var li=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=Rd(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Pd(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Xe(this.policyName,r),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),o&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{o&&(R+=`${A} - allowed: ${N} value: ${h.meters[A]??0}
81
81
  `),(h.meters[A]??0)>=N&&v.push(A)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",R),v.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(A,N,S)=>{if(o&&S.log.debug(`QuotaInboundPolicy: backend response - ${A.status}: ${A.statusText}`),!s.quotaOnStatusCodes.includes(A.status))return;let F=re.get(S,ci),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};o&&S.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let H=p.setQuota(d,z,S.requestId);S.waitUntil(H)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let o=re.get(e,ci)??{};Object.assign(o,t),re.set(e,ci,o)}static getUsage(e,t){let o=re.get(e,`${$a}-${t}`);if(o===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return o}static#e(e,t,o){re.set(e,`${$a}-${t}`,o)}};function Rd(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Ge(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}i(Rd,"validateAndParseOptions");function Pd(n,e){return encodeURIComponent(`${e}-${n}`)}i(Pd,"processKey");var Fa=ye("zuplo:policies:RateLimitInboundPolicy"),ja=i(async(n,e,t,o)=>{let r=Q.getLogger(e),s=i((H,C)=>{let q={};return(!H||H==="retry-after")&&(q[Tt]=C.toString()),E.tooManyRequests(n,e,void 0,q)},"rateLimited"),u=await xt(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Xe(o,r),v=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${o}/${c}`,R=await se(o,void 0,t),A=new ie(R,e),N=h.getCountAndUpdateExpiry(v,d,e.requestId),S;i(async()=>{let H=await N;if(H.count>l){let C=Date.now()+H.ttlSeconds*1e3;A.put(v,C,H.ttlSeconds),Fa(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${v}' (async mode)`),S=s(p,H.ttlSeconds)}},"asyncCheck")();let z=await A.get(v);if(z!==void 0&&z>Date.now()){Fa(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${v}' (async mode)`);let H=Math.round((z-Date.now())/1e3);return s(p,H)}return e.addResponseSendingHook(async H=>S??H),n},"AsyncRateLimitInboundPolicyImpl");var za=ye("zuplo:policies:RateLimitInboundPolicy"),Id="strict",Ba=i(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??Id)==="async")return ja(n,e,t,o);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Tt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await xt(o,t)(n,e,o),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,v=t.headerMode??"retry-after",R=Xe(o,a),N=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${o}/${p}`,S=await R.getCountAndUpdateExpiry(N,y,e.requestId);return S.count>h?(za(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(v,S.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;za(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var di;function Ga(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}i(Ga,"headersToNameValuePairs");function Ed(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}i(Ed,"queryToNameValueParis");function xd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(xd,"parseIntOrUndefined");var Va={};async function Td(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return di||(di={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ze(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ze(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:di,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ga(n.headers),queryString:Ed(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ga(a.headers),content:{size:xd(n.headers.get("content-length"))}}}]}}},d=Va[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",v=await Z.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${v.status}: '${await v.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),Va[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Td,"ReadmeMetricsInboundPolicy");var vd=i(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return r.forEach(u=>{s.delete(u)}),new ne(n,{headers:s})},"RemoveHeadersInboundPolicy");var Cd=i(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let s=o?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Od=i(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return r.forEach(u=>{s.searchParams.delete(u)}),new ne(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Sd=i(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),s=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(s,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Wa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ad=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Wa():s&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?Wa():n},"RequestSizeLimitInboundPolicy");var kt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Lt=i((n,e,t,o,r)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Gn(t,o,r,c.name),p=ge.instance.schemaValidator[d],h=p(e[c.name]),y=pi(p.errors);h||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),pi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ja(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=E.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",v,[o],y),Le(t.validateBody))return R}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?v:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=Vn(n.route.path,e.method,r),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?v:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=pi(l),h=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[o],p),Le(t.validateBody))return h}i(Ja,"handleBodyValidation");function Ka(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=kt(n),s=Lt(r.filter(a=>a.in==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Ka,"handleHeadersValidation");function Qa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=kt(n),r=Lt(o.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(Qa,"handlePathParameterValidation");function Ya(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=kt(n),r=Lt(o.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(Ya,"handleQueryParameterValidation");var Xa=i(async(n,e,t)=>{g("policy.inbound.request-validation");let o=Ya(e,n,t);if(o!==void 0||(o=Qa(e,n,t),o!==void 0)||(o=Ka(e,n,t),o!==void 0))return o;let r=await Ja(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),kd=Xa;var Ld=i(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var _d=i(async(n,e,t)=>(g("policy.inbound.set-body"),new ne(n,{body:t.body})),"SetBodyInboundPolicy");var Nd=i(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new ne(n,{headers:s})},"SetHeadersInboundPolicy");var Dd=i(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let s=o.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' 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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Md=i(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new ne(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ud=i(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var qd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Zd=i(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await qd(t.sleepInMs),n},"SleepInboundPolicy");var Hd=i(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,r,o);if(s instanceof Response)return s;if(!(s instanceof ne))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${o}' - 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?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var $d=i(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await se(o,void 0,t),s=new ie(r,e),a=await s.get(o);if(!a){let u=await Fd(t,e);s.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Fd(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Fd,"getAccessToken");var eu="https://accounts.google.com/o/oauth2/token",mi,jd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),mi||(mi=await Te.init(t.serviceAccountJson));let r={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(o,void 0,t),a=new ie(s,e),u=await a.get(o);if(!u){let c=await De({serviceAccount:mi,audience:eu,payload:r}),l=await In(eu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var zd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Bd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],gi,Gd=i(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Bd.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}gi||(gi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ze(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${o}`);let a=await se(o,void 0,t),u=new ie(a,e),c={uid:s,claims:r},l=await ut(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:gi,audience:zd,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Bs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var tn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let o=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await se("zuplo-token",void 0,t),s=await o.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await $n({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var tu="service-account-id-token",fi=class extends ce{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new je(this.cacheName):o=new ie(this.cacheName,t);let r=await o.get(tu);if(!r){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await tn.getIDToken(t,{audience:s}),u=await js(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await zs({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");r=l.token,o.put(tu,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${r}`),e}};var hi,Vd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),hi||(hi=await Te.init(t.serviceAccountJson));let r=await De({serviceAccount:hi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var nu="https://www.googleapis.com/oauth2/v4/token",yi,Wd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),yi||(yi=await Te.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=rt(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await se(o,void 0,t),a;t.useMemoryCacheOnly?a=new je(s):a=new ie(s,e);let u=await a.get(o);if(!u){let c=await De({serviceAccount:yi,audience:nu,payload:r}),l=await In(nu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Jd=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return n;let{errors:a}=t.validator.default;if(!a)throw new K("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 E.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ou=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=i((R,A)=>e(R,"name",{value:A,configurable:!0}),"__name"),r=i((R,A)=>i(function(){return A||(0,R[t(R)[0]])((A={exports:{}}).exports,A),A.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var A={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(S,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(S,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(S,F,z){return S},"updateTag")},N=o(function(S){return Object.assign({},A,S)},"buildOptions");R.buildOptions=N,R.defaultOptions=A}}),a=r({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var A=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=A+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S="["+A+"]["+N+"]*",F=new RegExp("^"+S+"$"),z=o(function(C,q){let V=[],j=q.exec(C);for(;j;){let x=[];x.startIndex=q.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=q.exec(C)}return V},"getAllMatches"),H=o(function(C){let q=F.exec(C);return!(q===null||typeof q>"u")},"isName");R.isExist=function(C){return typeof C<"u"},R.isEmptyObject=function(C){return Object.keys(C).length===0},R.merge=function(C,q,V){if(q){let j=Object.keys(q),x=j.length;for(let I=0;I<x;I++)V==="strict"?C[j[I]]=[q[j[I]]]:C[j[I]]=q[j[I]]}},R.getValue=function(C){return R.isExist(C)?C:""},R.isName=H,R.getAllMatches=z,R.nameRegexp=S}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,A){"use strict";var N=class{static{i(this,"XmlNode")}static{o(this,"XmlNode")}constructor(S){this.tagname=S,this.child=[],this[":@"]={}}add(S,F){S==="__proto__"&&(S="#__proto__"),this.child.push({[S]:F})}addChild(S){S.tagname==="__proto__"&&(S.tagname="#__proto__"),S[":@"]&&Object.keys(S[":@"]).length>0?this.child.push({[S.tagname]:S.child,":@":S[":@"]}):this.child.push({[S.tagname]:S.child})}};A.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,A){var N=a();function S(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,Ce="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&H(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&C(x,I))I+=8;else if(J&&q(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:Ce+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(S,"readDocType"),o(S,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),o(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),o(z,"isComment");function H(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="N"&&x[I+4]==="T"&&x[I+5]==="I"&&x[I+6]==="T"&&x[I+7]==="Y"}i(H,"isEntity"),o(H,"isEntity");function C(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(C,"isElement"),o(C,"isElement");function q(x,I){return x[I+1]==="!"&&x[I+2]==="A"&&x[I+3]==="T"&&x[I+4]==="T"&&x[I+5]==="L"&&x[I+6]==="I"&&x[I+7]==="S"&&x[I+8]==="T"}i(q,"isAttlist"),o(q,"isAttlist");function V(x,I){return x[I+1]==="!"&&x[I+2]==="N"&&x[I+3]==="O"&&x[I+4]==="T"&&x[I+5]==="A"&&x[I+6]==="T"&&x[I+7]==="I"&&x[I+8]==="O"&&x[I+9]==="N"}i(V,"isNotation"),o(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),o(j,"validateEntityName"),A.exports=S}}),l=r({"../../node_modules/strnum/strnum.js"(R,A){var N=/^[-+]?0x[a-fA-F0-9]+$/,S=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(C,q={}){if(q=Object.assign({},F,q),!C||typeof C!="string")return C;let V=C.trim();if(q.skipLike!==void 0&&q.skipLike.test(V))return C;if(q.hex&&N.test(V))return Number.parseInt(V,16);{let j=S.exec(V);if(j){let x=j[1],I=j[2],M=H(j[3]),le=j[4]||j[6];if(!q.leadingZeros&&I.length>0&&x&&V[2]!==".")return C;if(!q.leadingZeros&&I.length>0&&!x&&V[1]!==".")return C;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?q.eNotation?J:C:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:C:I?M===X||x+M===X?J:C:V===X||V===x+X?J:C}}else return C}}i(z,"toNumber"),o(z,"toNumber");function H(C){return C&&C.indexOf(".")!==-1&&(C=C.replace(/0+$/,""),C==="."?C="0":C[0]==="."?C="0"+C:C[C.length-1]==="."&&(C=C.substr(0,C.length-1))),C}i(H,"trimZeros"),o(H,"trimZeros"),A.exports=z}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,A){"use strict";var N=a(),S=u(),F=c(),z=l(),H=class{static{i(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=C,this.parseXml=I,this.parseTextData=q,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function C(P){let T=Object.keys(P);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(C,"addExternalEntities"),o(C,"addExternalEntities");function q(P,T,L,B,_,D,ee){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ee||(P=this.replaceEntitiesValue(P));let $=this.options.tagValueProcessor(T,P,L,_,D);return $==null?P:typeof $!=typeof P||$!==P?$:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(q,"parseTextData"),o(q,"parseTextData");function V(P){if(this.options.removeNSPrefix){let T=P.split(":"),L=P.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(P=L+T[1])}return P}i(V,"resolveNameSpace"),o(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(P,T,L){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=N.getAllMatches(P,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let $=this.resolveNameSpace(B[ee][1]),U=B[ee][4],pe=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(pe=this.options.transformAttributeName(pe)),pe==="__proto__"&&(pe="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let oe=this.options.attributeValueProcessor($,U,T);oe==null?D[pe]=U:typeof oe!=typeof U||oe!==U?D[pe]=oe:D[pe]=me(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[pe]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),o(x,"buildAttributesMap");var I=o(function(P){P=P.replace(/\r\n?/g,`
82
82
  `);let T=new S("!xml"),L=T,B="",_="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let $=b(P,">",D,"Closing Tag is not closed."),U=P.substring(D+2,$).trim();if(this.options.removeNSPrefix){let Se=U.indexOf(":");Se!==-1&&(U=U.substr(Se+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&(B=this.saveTextToParentTag(B,L,_));let pe=_.substring(_.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let oe=0;pe&&this.options.unpairedTags.indexOf(pe)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=$}else if(P[D+1]==="?"){let $=O(P,D,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new S($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,_,$.tagName)),this.addChild(L,U,_)}D=$.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let $=b(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=P.substring(D+4,$-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=$}else if(P.substr(D+1,2)==="!D"){let $=F(P,D);this.docTypeEntities=$.entities,D=$.i}else if(P.substr(D+1,2)==="!["){let $=b(P,"]]>",D,"CDATA is not closed.")-2,U=P.substring(D+9,$);B=this.saveTextToParentTag(B,L,_);let pe=this.parseTextData(U,L.tagname,_,!0,!1,!0,!0);pe==null&&(pe=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):L.add(this.options.textNodeName,pe),D=$+2}else{let $=O(P,D,this.options.removeNSPrefix),U=$.tagName,pe=$.rawTagName,oe=$.tagExp,Se=$.attrExpPresent,Ci=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let Oi=L;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),U!==T.tagname&&(_+=_?"."+U:U),this.isItStopNode(this.options.stopNodes,_,U)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=$.closeIndex;else{let Bn=this.readStopNodeData(P,pe,Ci+1);if(!Bn)throw new Error(`Unexpected end of ${pe}`);D=Bn.i,Oe=Bn.tagContent}let zn=new S(U);U!==oe&&Se&&(zn[":@"]=this.buildAttributesMap(oe,_,U)),Oe&&(Oe=this.parseTextData(Oe,U,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),zn.add(this.options.textNodeName,Oe),this.addChild(L,zn,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),_=_.substr(0,_.length-1),oe=U):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Oe=new S(U);U!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new S(U);this.tagsNodeStack.push(L),U!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Oe,_),L=Oe}B="",D=Ci}}else B+=P[D];return T.child},"parseXml");function M(P,T,L){let B=this.options.updateTag(T.tagname,L,T[":@"]);B===!1||(typeof B=="string"&&(T.tagname=B),P.addChild(T))}i(M,"addChild"),o(M,"addChild");var le=o(function(P){if(this.options.processEntities){for(let T in this.docTypeEntities){let L=this.docTypeEntities[T];P=P.replace(L.regx,L.val)}for(let T in this.lastEntities){let L=this.lastEntities[T];P=P.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let L=this.htmlEntities[T];P=P.replace(L.regex,L.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function J(P,T,L,B){return P&&(B===void 0&&(B=Object.keys(T.child).length===0),P=this.parseTextData(P,T.tagname,L,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&T.add(this.options.textNodeName,P),P=""),P}i(J,"saveTextToParentTag"),o(J,"saveTextToParentTag");function X(P,T,L){let B="*."+L;for(let _ in P){let D=P[_];if(B===D||T===D)return!0}return!1}i(X,"isItStopNode"),o(X,"isItStopNode");function Ce(P,T,L=">"){let B,_="";for(let D=T;D<P.length;D++){let ee=P[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===L[0])if(L[1]){if(P[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),o(Ce,"tagExpWithClosingIndex");function b(P,T,L,B){let _=P.indexOf(T,L);if(_===-1)throw new Error(B);return _+T.length-1}i(b,"findClosingIndex"),o(b,"findClosingIndex");function O(P,T,L,B=">"){let _=Ce(P,T+1,B);if(!_)return;let D=_.data,ee=_.index,$=D.search(/\s/),U=D,pe=!0;$!==-1&&(U=D.substring(0,$),D=D.substring($+1).trimStart());let oe=U;if(L){let Se=U.indexOf(":");Se!==-1&&(U=U.substr(Se+1),pe=U!==_.data.substr(Se+1))}return{tagName:U,tagExp:D,closeIndex:ee,attrExpPresent:pe,rawTagName:oe}}i(O,"readTagExp"),o(O,"readTagExp");function G(P,T,L){let B=L,_=1;for(;L<P.length;L++)if(P[L]==="<")if(P[L+1]==="/"){let D=b(P,">",L,`${T} is not closed`);if(P.substring(L+2,D).trim()===T&&(_--,_===0))return{tagContent:P.substring(B,L),i:D};L=D}else if(P[L+1]==="?")L=b(P,"?>",L+1,"StopNode is not closed.");else if(P.substr(L+1,3)==="!--")L=b(P,"-->",L+3,"StopNode is not closed.");else if(P.substr(L+1,2)==="![")L=b(P,"]]>",L,"StopNode is not closed.")-2;else{let D=O(P,L,">");D&&((D&&D.tagName)===T&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(G,"readStopNodeData"),o(G,"readStopNodeData");function me(P,T,L){if(T&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:z(P,L)}else return N.isExist(P)?P:""}i(me,"parseValue"),o(me,"parseValue"),A.exports=H}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function A(H,C){return N(H,C)}i(A,"prettify"),o(A,"prettify");function N(H,C,q){let V,j={};for(let x=0;x<H.length;x++){let I=H[x],M=S(I),le="";if(q===void 0?le=M:le=q+"."+M,M===C.textNodeName)V===void 0?V=I[M]:V+=""+I[M];else{if(M===void 0)continue;if(I[M]){let J=N(I[M],C,le),X=z(J,C);I[":@"]?F(J,I[":@"],le,C):Object.keys(J).length===1&&J[C.textNodeName]!==void 0&&!C.alwaysCreateTextNode?J=J[C.textNodeName]:Object.keys(J).length===0&&(C.alwaysCreateTextNode?J[C.textNodeName]="":J=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(J)):C.isArray(M,le,X)?j[M]=[J]:j[M]=J}}}return typeof V=="string"?V.length>0&&(j[C.textNodeName]=V):V!==void 0&&(j[C.textNodeName]=V),j}i(N,"compress"),o(N,"compress");function S(H){let C=Object.keys(H);for(let q=0;q<C.length;q++){let V=C[q];if(V!==":@")return V}}i(S,"propName"),o(S,"propName");function F(H,C,q,V){if(C){let j=Object.keys(C),x=j.length;for(let I=0;I<x;I++){let M=j[I];V.isArray(M,q+"."+M,!0,!0)?H[M]=[C[M]]:H[M]=C[M]}}}i(F,"assignAttributes"),o(F,"assignAttributes");function z(H,C){let{textNodeName:q}=C,V=Object.keys(H).length;return!!(V===0||V===1&&(H[q]||typeof H[q]=="boolean"||H[q]===0))}i(z,"isLeafTag"),o(z,"isLeafTag"),R.prettify=A}}),h=r({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var A=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},N,O);let G=[],me=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let T=0;T<b.length;T++)if(b[T]==="<"&&b[T+1]==="?"){if(T+=2,T=F(b,T),T.err)return T}else if(b[T]==="<"){let L=T;if(T++,b[T]==="!"){T=z(b,T);continue}else{let B=!1;b[T]==="/"&&(B=!0,T++);let _="";for(;T<b.length&&b[T]!==">"&&b[T]!==" "&&b[T]!==" "&&b[T]!==`
83
83
  `&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let $;return _.trim().length===0?$="Invalid space after '<'.":$="Tag '"+_+"' is an invalid name.",M("InvalidTag",$,X(b,T))}let D=q(b,T);if(D===!1)return M("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,T));let ee=D.value;if(T=D.index,ee[ee.length-1]==="/"){let $=T-ee.length;ee=ee.substring(0,ee.length-1);let U=j(ee,O);if(U===!0)me=!0;else return M(U.err.code,U.err.msg,X(b,$+U.err.line))}else if(B)if(D.tagClosed){if(ee.trim().length>0)return M("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let $=G.pop();if(_!==$.tagName){let U=X(b,$.tagStartPos);return M("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(P=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let $=j(ee,O);if($!==!0)return M($.err.code,$.err.msg,X(b,T-ee.length+$.err.line));if(P===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let $=I(b,T);if($==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=$}else if(P===!0&&!S(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(S(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(b){return b===" "||b===" "||b===`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.35.14",
4
+ "version": "6.38.0",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {