@zuplo/runtime 5.2340.0 → 5.2342.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/cjs/index.js +1 -1
- package/out/esm/index.js +1 -1
- package/out/types/index.d.ts +29 -337
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -58,7 +58,7 @@ Signature verification is impossible without access to the original signed mater
|
|
|
58
58
|
`+d}):new De(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
59
59
|
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.
|
|
60
60
|
`+l+`
|
|
61
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(nc,"validateComputedSignature");function rc(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(rc,"parseHeader");function oc(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(oc,"secureCompare");async function ic(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=bo[i[u]];return a.join("")}s(ic,"computeHMACSignatureAsync");var bo=new Array(256);for(let n=0;n<bo.length;n++)bo[n]=n.toString(16).padStart(2,"0");function Y(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Xe(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} 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 ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} 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 ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(Y,"optionValidator");var jt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){Y(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Ss(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="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",i),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Cs(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}s(Cs,"isStripeWebhookEvent");var sc={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o}},En=sc;var wo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Os="My API Key";async function As({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,wo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Os,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await fe({retryDelayMs:5,retries:2,logger:X.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}s(As,"createConsumer");async function Ls({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,wo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Os,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(i)},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 i.log.error(h,p),new k(h)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Ls,"createConsumerInvite");async function ks({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=f.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,wo);o.searchParams.set("with-api-key","true");let i=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.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}s(ks,"deleteConsumer");async function _s({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,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(!it(p))throw new W("No Zuplo JWT token set.");let y=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await y.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new k(`${O} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}s(_s,"createSubscription");async function dt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,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(r)}'.`)}s(dt,"updateSubscription");async function pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"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]}s(pt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Be="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function xn(n){return n.replaceAll("_","-")}s(xn,"stripeStatusToMeteringStatus");function tt(n){return new Date(n*1e3).toISOString()}s(tt,"unixTimestampToISOString");async function Ro(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:re,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}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});let u=i.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 As({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await En.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:re,detail:p.message})}if(!c)return x.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=xn(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:tt(t.data.object.trial_end),trialStartDate:tt(t.data.object.trial_start)}),await _s({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await ks({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:re,detail:p.message})}return x.ok(n,e,{title:Be})}s(Ro,"onCustomerSubscriptionCreated");async function Po(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});try{let a=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await dt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}s(Po,"onCustomerSubscriptionDeleted");async function Io(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=xn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=tt(t.data.object.trial_end)),await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await En.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.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 dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?tt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?tt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:re,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."+Ie})}s(Io,"onCustomerSubscriptionUpdated");var Ns=class extends Xt{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(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 W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!ac(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Cs(y))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Ro(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Io(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Po(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:re,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.`+Ie})}},"stripeWebhookHandler"),i=Wi({inboundPolicies:[new jt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});Y(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[be,i],handler:o,gateway:r}),u=new se({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function ac(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(ac,"isMetricsRegion");var Ms=new WeakMap,Ds={},Eo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ms.set(e,t)}};async function uc(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=st(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ms.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=Ye(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=Ds[t.apiKey];if(!h){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";h=new J("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${S.message}`),S}}),Ds[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}s(uc,"AmberfloMeteringInboundPolicy");async function Tn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(Tn,"sha256");var Hs=new Map;async function le(n,e,t){let r,o=`${n}-${e}`,i=Hs.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await Tn(JSON.stringify({policyName:n,options:t}))}`,Hs.set(n,r)),r}s(le,"getPolicyCacheName");var Us="key-metadata-cache-type";function cc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(cc,"getKeyValue");async function xo(n,e,t,r){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 '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(S=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:S}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=cc(a,o);if(!u||u==="")return i("No key present");let c=await lc(u),l=await le(r,void 0,o),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!==Us&&X.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},y=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(y.status!==200){try{let S=await y.text(),H=JSON.parse(S);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:Us,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(xo,"ApiKeyInboundPolicy");async function lc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(lc,"hashValue");var dc=xo;import{createRemoteJWKSet as mc,jwtVerify as Zs}from"jose";import{createLocalJWKSet as pc}from"jose";var To=class{constructor(e,t,r){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:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(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(r){if(r instanceof vo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}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=pc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await F.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new So("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new mt("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 mt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function qs(n,e,t){let r=new To(n,e,t);return async(o,i)=>r.getKey(o,i)}s(qs,"createRemoteJWKSet");var mt=class extends k{static{s(this,"JWKSError")}},vo=class extends mt{static{s(this,"JWKSNoMatchingKey")}},So=class extends mt{static{s(this,"JWKSTimeout")}};var vn={},gc=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await le(n,void 0,r),u=new ie(a,e);vn[r.jwkUrl]=qs(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else vn[r.jwkUrl]=mc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Zs(t,vn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),fc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await Zs(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),we=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?gc(r,e):fc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var hc=s(async(n,e,t,r)=>(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},r)),"Auth0JwtInboundPolicy");var Co=class n extends pe{static{s(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"),Y(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new si(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);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),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.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(r,t,a)}}addAttributesToCategory(e,t,r){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(...r)}};var yc=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===h&&P.password===y);return O||await i("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 Sn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Sn,"extractDateElements");function Fs(n,e){return new Date(n,e+1,0).getDate()}s(Fs,"getDaysInMonth");function Oo(n,e){return n<=e?e-n:6-n+e+1}s(Oo,"getDaysBetweenWeekdays");var Cn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,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(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.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(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((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(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=Fs(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).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"?Oo(d,p):Oo(p,d);l=e==="next"?o+h:o-h,(l>i||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=Sn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+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 r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Sn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+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 r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Sn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var bc={min:0,max:59},wc={min:0,max:59},Rc={min:0,max:23},Pc={min:1,max:31},Ic={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"}},Ec={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},xc={"@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 nt(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 r=n.split(",");if(r.length>1)return r.forEach(d=>{nt(d,e).forEach(h=>t.add(h))}),t;let o=s(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"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[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}s(nt,"parseElement");function Ao(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=xc[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",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=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 Cn({seconds:nt(t,bc),minutes:nt(r,wc),hours:nt(o,Rc),days:nt(i,Pc),months:new Set(Array.from(nt(a,Ic)).map(c=>c-1)),weekdays:new Set(Array.from(nt(u,Ec)).map(c=>c%7))})}s(Ao,"parseCronExpression");var Lo=class extends pe{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),Y(e,t).optional("problem","object"),e.problem&&Y(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(r=>typeof r!="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=[Ao(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ao(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=x.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 x.format(i,e,t)}return e}};var Tc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function vc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(vc,"digestMessage");var Sc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await vc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Cc(n,e,t,r){g("policy.inbound.caching");let o=await le(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Sc(n,t),c=await i.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);Tc.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(Cc,"CachingInboundPolicy");var Oc=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ac=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var Lc=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var kc=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var _c=s(async(n,e,t,r)=>{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},r)},"CognitoJwtInboundPolicy");var Bs=Ve(Ge());var On=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ko=class extends On{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},_o=class extends On{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Nc(n,e){if(Zi(n))throw new ko(e)}s(Nc,"throwIfUndefinedOrNull");function zt(n,e){if(Nc(n,e),!Ee(n))throw new _o(e,"string")}s(zt,"throwIfNotString");var An=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return zt(e,"redisClientUrl"),zt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){zt(e,"url");let i=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(zt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new W("The in-memory rate limit client does not support this request")}};var Dc=s(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 gt(n,e){return{function:qc(e,"RateLimitInboundPolicy",n),user:Hc,ip:Mc,all:Uc}[e.rateLimitBy??"ip"]}s(gt,"getRateLimitByFunctions");var Mc=s(async n=>({key:`ip-${Dc(n)}`}),"getIP"),Hc=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Uc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),kn;function ft(n,e){let t;if(kn)return kn;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new Ln,kn=t,t;let{authApiJWT:r,redisURL:o}=f.instance;if(!Ee(o))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(r))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=An.initialize(o,r,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!t||!t.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return kn=t,t}s(ft,"getRedisClient");async function _n(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(_n,"getCountAndUpdateExpiry");async function $s(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s($s,"multiCount");async function js(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(js,"multiIncrement");function qc(n,e,t){let r;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(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,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")}s(qc,"wrapUserFunction");var ht="Retry-After";var zs=(0,Bs.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),No=Symbol("complex-rate-limit-counters"),Do=class n extends pe{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=ge.get(e,No)??{};Object.assign(r,t),ge.set(e,No,t)}static getIncrements(e){return ge.get(e,No)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),Y(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&&Y(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=X.getLogger(t),i=ft(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[ht]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await gt(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 S=n.getIncrements(t);zs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let H=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:h,increment:S[j]??0})),_=js(H,i,t.requestId);t.waitUntil(_),await _}catch(S){t.log.error(S)}});let y=Object.entries(p).map(([S,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:h,limit:H})),O=await $s(y,i,t.requestId);return Zc(O,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;zs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Zc(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Zc,"findOverLimits");var Fc=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,i=_t(t.policies,o?.routeData.policies);return vr(i)(n,e)},"CompositeInboundPolicy");var $c=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=jc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await le(r,void 0,t),u=new ie(a,e),c=await u.get(i);if(!c){let l=await F.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="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function jc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(jc,"getToken");var zc=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),Y(t,r).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},r)),"FirebaseJwtInboundPolicy");var Bc=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{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 te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var yt="__unknown__",Vc=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:wt(t.allow?.countries,"allow.countries",r),regionCodes:wt(t.allow?.regionCodes,"allow.regionCode",r),asns:wt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:wt(t.block?.countries,"block.countries",r),regionCodes:wt(t.block?.regionCodes,"block.regionCode",r),asns:wt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??yt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??yt,u=e.incomingRequestProperties.asn?.toString()??yt,c=o.ignoreUnknown&&i===yt,l=o.ignoreUnknown&&a===yt,d=o.ignoreUnknown&&u===yt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return bt(n,e,r,i,a,u);let O=o.block.countries,P=o.block.regionCodes,S=o.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?bt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function bt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(bt,"blockedResponse");function wt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(wt,"toLowerStringArray");var Gc=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Wc=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Mo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Mo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(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 Vs(a[u])}else return a.length>0?Vs(a[0]):Mo(r,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 Vs(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})}}s(Vs,"generateResponse");var Mo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Kc="Incoming",Jc={logRequestBody:!0,logResponseBody:!0};function Gs(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Gs,"headersToObject");function Ws(){return new Date().toISOString()}s(Ws,"timestamp");var Ho=new WeakMap,Xc={};function Yc(n,e){let t=Ho.get(n);t||(t=Xc);let r=Object.assign({...t},e);Ho.set(n,r)}s(Yc,"setMoesifContext");async function Ks(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(Ks,"readBody");var Qc={},Uo;function Js(){if(!Uo)throw new k("Invalid State - no _lastLogger");return Uo}s(Js,"getLastLogger");function el(n){let e=Qc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Js().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Js().error({status:o.status,body:await o.text()})})),e}s(el,"getDispatcher");async function tl(n,e,t,r){g("policy.inbound.moesif-analytics"),Uo=e.log;let o=Ws(),i=Object.assign(Jc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ks(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=el(i.applicationId),d=n.headers.get("true-client-ip"),p=Ho.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Gs(n.headers)},y=i.logResponseBody?await Ks(u,e):void 0,O={time:Ws(),status:u.status,headers:Gs(u.headers),body:y},P={request:h,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Kc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(tl,"MoesifInboundPolicy");async function Xs(n,e,t,r){let o=X.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=f.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"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}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.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]}s(Xs,"loadSubscription");async function Ys(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=f.instance,u=X.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});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)}}s(Ys,"consumeSubcriptionQuotas");var nl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Nn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);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}}s(Nn,"validateMeters");function Qs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Qe(n),r=[];for(let o of t)nl.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.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"]}s(Qs,"parseAllowedSubscriptionStatuses");function ea(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(ea,"compareMeters");var qo=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,Tt)}static setMeters(e,t){Nn(t,"setMeters"),ge.set(e,Kt,t)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){Y(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=st(this.options.meterOnStatusCodes),i=ge.get(t,Kt),a={...this.options.meters,...i};Nn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Qs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,H)=>{let _=ge.get(H,Tt);if((this.options.allowRequestsWithoutSubscription??!1)&&!_){H.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 q=ge.get(H,Kt),$={...this.options.meters,...q};if(Nn($,this.policyName),o.includes(P.status)&&_&&$){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${_.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:M}=ea(_.meters,$);if(M&&Object.keys(M).length>0){let V=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Ys(H,_.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.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 Xs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.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.`),x.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`),ge.set(t,Tt,p));let h=ge.get(t,Tt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.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}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Dn(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 r=await fe({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(r.status!==200){try{let i=await r.text();e.log.error("Error getting token from identity provider.",i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(Dn,"getClientCredentialsAccessToken");var Rt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},Mn=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Rt("unknown",`Unknown error. Status: ${c.status}`):new Rt(l.code,l.message)}return c.json()}};function Bt(n,e,t){!n[e]&&t&&(n[e]=t)}s(Bt,"setHeaderIfNotSet");var ta="X-OpenFGA-Client-Method",na="X-OpenFGA-Client-Bulk-Request-Id",Vt=class extends Mn{static{s(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:r={}}=t;return Bt(r,ta,"BatchCheck"),Bt(r,na,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Rt)throw a;return{allowed:void 0,error:a,_request:i}})))}}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:r,object:o,relations:i,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Bt(c,ta,"ListRelations"),Bt(c,na,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,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 ra=Symbol("openfga-authz-context-data"),Pt=class extends pe{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];ge.set(e,ra,r)}constructor(e,t){if(super(e,t),Y(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")Y(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")Y(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")Y(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 Vt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await le(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ge.get(t,ra);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});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),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new W(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await Dn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var oa=["us1","eu1","au1"],Zo=class extends Pt{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!oa.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${oa.join(", ")}.`);let r={...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(r,t),g("policy.inbound.oktafga-authz")}};var rl=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Fo=class extends Pt{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as ol}from"jose";var $o,il=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!$o)try{$o=await ol(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return we(n,e,{issuer:t.authUrl,secret:$o,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ca=Ve(Ge());var sa=Ve(Ge());var ia=(0,sa.debug)("zuplo:policies:RateLimitInboundPolicy"),aa=s(async(n,e,t,r)=>{let o=X.getLogger(e),i=s(($,E)=>{let M={};return(!$||$==="retry-after")&&(M[ht]=E.toString()),x.tooManyRequests(n,e,void 0,M)},"rateLimited"),u=await gt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=ft(r,o),O=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${r}/${c}`,P=await le(r,void 0,t),S=new ie(P,e),H=_n(O,d,h,e.requestId),_;s(async()=>{let $=await H;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;S.put(O,E,$.ttlSeconds),ia(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),_=i(p,$.ttlSeconds)}},"asyncCheck")();let q=await S.get(O);if(q!==void 0&&q>Date.now()){ia(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return i(p,$)}return e.addResponseSendingHook(async $=>_??$),n},"AsyncRateLimitInboundPolicy");var ua=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),sl="strict",la=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??sl)==="async")return aa(n,e,t,r);let i=Date.now(),a=X.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[ht]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await gt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=ft(r,a),H=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${r}/${p}`,_=await _n(H,y,P,e.requestId);return _.count>h?(ua(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(O,_.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;ua(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var jo;function da(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(da,"headersToNameValuePairs");function al(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(al,"queryToNameValueParis");function ul(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(ul,"parseIntOrUndefined");var pa={};async function cl(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return jo||(jo={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?Ye(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ye(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:jo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:da(n.headers),queryString:al(n.query)},response:{status:a.status,statusText:a.statusText,headers:da(a.headers),content:{size:ul(n.headers.get("content-length"))}}}]}}},d=pa[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",O=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),pa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(cl,"ReadmeMetricsInboundPolicy");var ll=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new te(n,{headers:i})},"RemoveHeadersInboundPolicy");var dl=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var pl=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new te(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var ml=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ma=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),gl=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?ma():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ma():n},"RequestSizeLimitInboundPolicy");var It=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Et=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Fn(t,r,o,c.name),p=he.instance.schemaValidator[d],h=p(e[c.name]),y=zo(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ae=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),zo=s(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 ga(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",O,[r],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=$n(n.route.path,e.method,o),u=he.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")}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=zo(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return h}s(ga,"handleBodyValidation");function fa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=It(n),i=Et(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ae(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Le(t.validateHeaders))return u}}s(fa,"handleHeadersValidation");function ha(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}s(ha,"handlePathParameterValidation");function ya(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}s(ya,"handleQueryParameterValidation");var ba=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=ya(e,n,t);if(r!==void 0||(r=ha(e,n,t),r!==void 0)||(r=fa(e,n,t),r!==void 0))return r;let o=await ga(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),fl=ba;var hl=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var yl=s(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var bl=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new te(n,{headers:i})},"SetHeadersInboundPolicy");var wl=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Rl=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new te(i.toString(),n)},"SetQueryParamsInboundPolicy");var Pl=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Il=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),El=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Il(t.sleepInMs),n},"SleepInboundPolicy");var xl=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),Y(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await we(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Tl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),Y(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await le(r,void 0,t),i=new ie(o,e),a=await i.get(r);if(!a){let u=await vl(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function vl(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await fe({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(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(vl,"getAccessToken");var wa="https://accounts.google.com/o/oauth2/token",Bo,Sl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),Y(t,r).required("serviceAccountJson","string"),Bo||(Bo=await xe.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await le(r,void 0,t),a=new ie(i,e),u=await a.get(r);if(!u){let c=await _e({serviceAccount:Bo,audience:wa,payload:o}),l=await dn(wa,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(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Cl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Ol=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vo,Al=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),Y(t,r).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 '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Ol.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Vo||(Vo=await xe.init(t.serviceAccountJson));let i=t.userId;if(!i&&!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?.");i=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?`);i=Ye(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await le(r,void 0,t),u=new ie(a,e),c={uid:i,claims:o},l=await Tn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await _e({serviceAccount:Vo,audience:Cl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await os(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 Go,Ll=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),Y(t,r).required("audience","string").required("serviceAccountJson","string"),Go||(Go=await xe.init(t.serviceAccountJson));let o=await _e({serviceAccount:Go,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ra="https://www.googleapis.com/oauth2/v4/token",Wo,kl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),Y(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Wo||(Wo=await xe.init(t.serviceAccountJson));let o={};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=Qe(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await le(r,void 0,t),a;t.useMemoryCacheOnly?a=new rt(i):a=new ie(i,e);let u=await a.get(r);if(!u){let c=await _e({serviceAccount:Wo,audience:Ra,payload:o}),l=await dn(Ra,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(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var _l=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new W("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Pa=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),o=s((P,S)=>s(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={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:function(_,j){return j},attributeValueProcessor:function(_,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(_,j,q){return _}},H=r(function(_){return Object.assign({},S,_)},"buildOptions");P.buildOptions=H,P.defaultOptions=S}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":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",H=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",_="["+S+"]["+H+"]*",j=new RegExp("^"+_+"$"),q=r(function(E,M){let V=[],G=M.exec(E);for(;G;){let v=[];v.startIndex=M.lastIndex-G[0].length;let T=G.length;for(let U=0;U<T;U++)v.push(G[U]);V.push(v),G=M.exec(E)}return V},"getAllMatches"),$=r(function(E){let M=j.exec(E);return!(M===null||typeof M>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,M,V){if(M){let G=Object.keys(M),v=G.length;for(let T=0;T<v;T++)V==="strict"?E[G[T]]=[M[G[T]]]:E[G[T]]=M[G[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=_}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var H=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(_){this.tagname=_,this.child=[],this[":@"]={}}add(_,j){_==="__proto__"&&(_="#__proto__"),this.child.push({[_]:j})}addChild(_){_.tagname==="__proto__"&&(_.tagname="#__proto__"),_[":@"]&&Object.keys(_[":@"]).length>0?this.child.push({[_.tagname]:_.child,":@":_[":@"]}):this.child.push({[_.tagname]:_.child})}};S.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var H=a();function _(v,T){let U={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let ue=1,K=!1,Q=!1,ve="";for(;T<v.length;T++)if(v[T]==="<"&&!Q){if(K&&$(v,T))T+=7,[entityName,val,T]=j(v,T+1),val.indexOf("&")===-1&&(U[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(v,T))T+=8;else if(K&&M(v,T))T+=8;else if(K&&V(v,T))T+=9;else if(q)Q=!0;else throw new Error("Invalid DOCTYPE");ue++,ve=""}else if(v[T]===">"){if(Q?v[T-1]==="-"&&v[T-2]==="-"&&(Q=!1,ue--):ue--,ue===0)break}else v[T]==="["?K=!0:ve+=v[T];if(ue!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}s(_,"readDocType"),r(_,"readDocType");function j(v,T){let U="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)U+=v[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ue=v[T++],K="";for(;T<v.length&&v[T]!==ue;T++)K+=v[T];return[U,K,T]}s(j,"readEntityExp"),r(j,"readEntityExp");function q(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}s(q,"isComment"),r(q,"isComment");function $(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}s($,"isEntity"),r($,"isEntity");function E(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}s(E,"isElement"),r(E,"isElement");function M(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}s(M,"isAttlist"),r(M,"isAttlist");function V(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),S.exports=_}}),l=o({"../../node_modules/strnum/strnum.js"(P,S){var H=/^[-+]?0x[a-fA-F0-9]+$/,_=/^([\-\+])?(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 j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,M={}){if(M=Object.assign({},j,M),!E||typeof E!="string")return E;let V=E.trim();if(M.skipLike!==void 0&&M.skipLike.test(V))return E;if(M.hex&&H.test(V))return Number.parseInt(V,16);{let G=_.exec(V);if(G){let v=G[1],T=G[2],U=$(G[3]),ue=G[4]||G[6];if(!M.leadingZeros&&T.length>0&&v&&V[2]!==".")return E;if(!M.leadingZeros&&T.length>0&&!v&&V[1]!==".")return E;{let K=Number(V),Q=""+K;return Q.search(/[eE]/)!==-1||ue?M.eNotation?K:E:V.indexOf(".")!==-1?Q==="0"&&U===""||Q===U||v&&Q==="-"+U?K:E:T?U===Q||v+U===Q?K:E:V===Q||V===v+Q?K:E}}else return E}}s(q,"toNumber"),r(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s($,"trimZeros"),r($,"trimZeros"),S.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var H=a(),_=u(),j=c(),q=l(),$=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=M,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ue,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let z=I[A];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function M(R,I,A,z,L,N,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let Z=this.options.tagValueProcessor(I,R,A,L,N);return Z==null?R:typeof Z!=typeof R||Z!==R?Z:this.options.trimValues?ce(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?ce(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(M,"parseTextData"),r(M,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,G),L=z.length,N={};for(let ee=0;ee<L;ee++){let Z=this.resolveNameSpace(z[ee][1]),D=z[ee][4],oe=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ne=this.options.attributeValueProcessor(Z,D,I);ne==null?N[oe]=D:typeof ne!=typeof D||ne!==D?N[oe]=ne:N[oe]=ce(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[oe]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
|
|
61
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(nc,"validateComputedSignature");function rc(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(rc,"parseHeader");function oc(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(oc,"secureCompare");async function ic(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=bo[i[u]];return a.join("")}s(ic,"computeHMACSignatureAsync");var bo=new Array(256);for(let n=0;n<bo.length;n++)bo[n]=n.toString(16).padStart(2,"0");function Y(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Xe(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} 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 ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} 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 ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(Y,"optionValidator");var jt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){Y(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Ss(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="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",i),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Cs(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}s(Cs,"isStripeWebhookEvent");var sc={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o}},En=sc;var wo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Os="My API Key";async function As({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,wo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Os,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await fe({retryDelayMs:5,retries:2,logger:X.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}s(As,"createConsumer");async function Ls({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,wo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Os,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(i)},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 i.log.error(h,p),new k(h)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Ls,"createConsumerInvite");async function ks({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=f.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,wo);o.searchParams.set("with-api-key","true");let i=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.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}s(ks,"deleteConsumer");async function _s({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,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(!it(p))throw new W("No Zuplo JWT token set.");let y=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await y.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new k(`${O} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}s(_s,"createSubscription");async function dt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,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(r)}'.`)}s(dt,"updateSubscription");async function pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"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]}s(pt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Be="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function xn(n){return n.replaceAll("_","-")}s(xn,"stripeStatusToMeteringStatus");function tt(n){return new Date(n*1e3).toISOString()}s(tt,"unixTimestampToISOString");async function Ro(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:re,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}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});let u=i.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 As({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await En.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:re,detail:p.message})}if(!c)return x.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=xn(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:tt(t.data.object.trial_end),trialStartDate:tt(t.data.object.trial_start)}),await _s({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await ks({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:re,detail:p.message})}return x.ok(n,e,{title:Be})}s(Ro,"onCustomerSubscriptionCreated");async function Po(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});try{let a=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await dt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}s(Po,"onCustomerSubscriptionDeleted");async function Io(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Ie});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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=xn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=tt(t.data.object.trial_end)),await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await En.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.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 dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}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:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?tt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?tt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:re,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. `+Ie})}return x.ok(n,e,{title:Be})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:re,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."+Ie})}s(Io,"onCustomerSubscriptionUpdated");var Ns=class extends Xt{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(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 W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!ac(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Cs(y))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Ro(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Io(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Po(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:re,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.`+Ie})}},"stripeWebhookHandler"),i=Wi({inboundPolicies:[new jt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});Y(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[be,i],handler:o,gateway:r}),u=new se({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function ac(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(ac,"isMetricsRegion");var Ms=new WeakMap,Ds={},Eo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ms.set(e,t)}};async function uc(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=st(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ms.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=Ye(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=Ds[t.apiKey];if(!h){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";h=new J("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${S.message}`),S}}),Ds[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}s(uc,"AmberfloMeteringInboundPolicy");async function Tn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(Tn,"sha256");var Hs=new Map;async function le(n,e,t){let r,o=`${n}-${e}`,i=Hs.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await Tn(JSON.stringify({policyName:n,options:t}))}`,Hs.set(n,r)),r}s(le,"getPolicyCacheName");var Us="key-metadata-cache-type";function cc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(cc,"getKeyValue");async function xo(n,e,t,r){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 '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(S=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:S}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=cc(a,o);if(!u||u==="")return i("No key present");let c=await lc(u),l=await le(r,void 0,o),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!==Us&&X.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},y=await fe({retryDelayMs:5,retries:2,logger:X.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(y.status!==200){try{let S=await y.text(),H=JSON.parse(S);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:Us,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(xo,"ApiKeyInboundPolicy");async function lc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(lc,"hashValue");var dc=xo;import{createRemoteJWKSet as mc,jwtVerify as Zs}from"jose";import{createLocalJWKSet as pc}from"jose";var To=class{constructor(e,t,r){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:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(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(r){if(r instanceof vo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}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=pc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await F.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new So("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new mt("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 mt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function qs(n,e,t){let r=new To(n,e,t);return async(o,i)=>r.getKey(o,i)}s(qs,"createRemoteJWKSet");var mt=class extends k{static{s(this,"JWKSError")}},vo=class extends mt{static{s(this,"JWKSNoMatchingKey")}},So=class extends mt{static{s(this,"JWKSTimeout")}};var vn={},gc=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await le(n,void 0,r),u=new ie(a,e);vn[r.jwkUrl]=qs(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else vn[r.jwkUrl]=mc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Zs(t,vn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),fc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await Zs(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),we=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?gc(r,e):fc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var hc=s(async(n,e,t,r)=>(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},r)),"Auth0JwtInboundPolicy");var Co=class n extends pe{static{s(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"),Y(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new si(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);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),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.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(r,t,a)}}addAttributesToCategory(e,t,r){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(...r)}};var yc=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===h&&P.password===y);return O||await i("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 Sn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Sn,"extractDateElements");function Fs(n,e){return new Date(n,e+1,0).getDate()}s(Fs,"getDaysInMonth");function Oo(n,e){return n<=e?e-n:6-n+e+1}s(Oo,"getDaysBetweenWeekdays");var Cn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,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(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.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(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((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(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=Fs(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).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"?Oo(d,p):Oo(p,d);l=e==="next"?o+h:o-h,(l>i||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=Sn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+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 r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Sn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+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 r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Sn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var bc={min:0,max:59},wc={min:0,max:59},Rc={min:0,max:23},Pc={min:1,max:31},Ic={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"}},Ec={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},xc={"@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 nt(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 r=n.split(",");if(r.length>1)return r.forEach(d=>{nt(d,e).forEach(h=>t.add(h))}),t;let o=s(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"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[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}s(nt,"parseElement");function Ao(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=xc[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",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=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 Cn({seconds:nt(t,bc),minutes:nt(r,wc),hours:nt(o,Rc),days:nt(i,Pc),months:new Set(Array.from(nt(a,Ic)).map(c=>c-1)),weekdays:new Set(Array.from(nt(u,Ec)).map(c=>c%7))})}s(Ao,"parseCronExpression");var Lo=class extends pe{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),Y(e,t).optional("problem","object"),e.problem&&Y(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(r=>typeof r!="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=[Ao(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ao(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=x.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 x.format(i,e,t)}return e}};var Tc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function vc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(vc,"digestMessage");var Sc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await vc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Cc(n,e,t,r){g("policy.inbound.caching");let o=await le(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Sc(n,t),c=await i.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);Tc.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(Cc,"CachingInboundPolicy");var Oc=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ac=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var Lc=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var kc=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var _c=s(async(n,e,t,r)=>{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},r)},"CognitoJwtInboundPolicy");var Bs=Ve(Ge());var On=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ko=class extends On{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},_o=class extends On{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Nc(n,e){if(Zi(n))throw new ko(e)}s(Nc,"throwIfUndefinedOrNull");function zt(n,e){if(Nc(n,e),!Ee(n))throw new _o(e,"string")}s(zt,"throwIfNotString");var An=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return zt(e,"redisClientUrl"),zt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){zt(e,"url");let i=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(zt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new W("The in-memory rate limit client does not support this request")}};var Dc=s(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 gt(n,e){return{function:qc(e,"RateLimitInboundPolicy",n),user:Hc,ip:Mc,all:Uc}[e.rateLimitBy??"ip"]}s(gt,"getRateLimitByFunctions");var Mc=s(async n=>({key:`ip-${Dc(n)}`}),"getIP"),Hc=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Uc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),kn;function ft(n,e){let t;if(kn)return kn;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new Ln,kn=t,t;let{authApiJWT:r,redisURL:o}=f.instance;if(!Ee(o))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(r))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=An.initialize(o,r,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!t||!t.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return kn=t,t}s(ft,"getRedisClient");async function _n(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(_n,"getCountAndUpdateExpiry");async function $s(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s($s,"multiCount");async function js(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(js,"multiIncrement");function qc(n,e,t){let r;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(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,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")}s(qc,"wrapUserFunction");var ht="Retry-After";var zs=(0,Bs.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),No=Symbol("complex-rate-limit-counters"),Do=class n extends pe{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=ge.get(e,No)??{};Object.assign(r,t),ge.set(e,No,t)}static getIncrements(e){return ge.get(e,No)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),Y(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&&Y(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=X.getLogger(t),i=ft(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[ht]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await gt(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 S=n.getIncrements(t);zs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let H=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:h,increment:S[j]??0})),_=js(H,i,t.requestId);t.waitUntil(_),await _}catch(S){t.log.error(S)}});let y=Object.entries(p).map(([S,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:h,limit:H})),O=await $s(y,i,t.requestId);return Zc(O,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;zs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Zc(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Zc,"findOverLimits");var Fc=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,i=_t(t.policies,o?.routeData.policies);return vr(i)(n,e)},"CompositeInboundPolicy");var $c=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=jc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await le(r,void 0,t),u=new ie(a,e),c=await u.get(i);if(!c){let l=await F.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="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function jc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(jc,"getToken");var zc=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),Y(t,r).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},r)),"FirebaseJwtInboundPolicy");var Bc=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{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 te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var yt="__unknown__",Vc=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:wt(t.allow?.countries,"allow.countries",r),regionCodes:wt(t.allow?.regionCodes,"allow.regionCode",r),asns:wt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:wt(t.block?.countries,"block.countries",r),regionCodes:wt(t.block?.regionCodes,"block.regionCode",r),asns:wt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??yt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??yt,u=e.incomingRequestProperties.asn?.toString()??yt,c=o.ignoreUnknown&&i===yt,l=o.ignoreUnknown&&a===yt,d=o.ignoreUnknown&&u===yt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return bt(n,e,r,i,a,u);let O=o.block.countries,P=o.block.regionCodes,S=o.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?bt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function bt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(bt,"blockedResponse");function wt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(wt,"toLowerStringArray");var Gc=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Wc=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Mo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Mo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(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 Vs(a[u])}else return a.length>0?Vs(a[0]):Mo(r,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 Vs(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})}}s(Vs,"generateResponse");var Mo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Kc="Incoming",Jc={logRequestBody:!0,logResponseBody:!0};function Gs(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Gs,"headersToObject");function Ws(){return new Date().toISOString()}s(Ws,"timestamp");var Ho=new WeakMap,Xc={};function Yc(n,e){let t=Ho.get(n);t||(t=Xc);let r=Object.assign({...t},e);Ho.set(n,r)}s(Yc,"setMoesifContext");async function Ks(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(Ks,"readBody");var Qc={},Uo;function Js(){if(!Uo)throw new k("Invalid State - no _lastLogger");return Uo}s(Js,"getLastLogger");function el(n){let e=Qc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Js().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Js().error({status:o.status,body:await o.text()})})),e}s(el,"getDispatcher");async function tl(n,e,t,r){g("policy.inbound.moesif-analytics"),Uo=e.log;let o=Ws(),i=Object.assign(Jc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ks(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=el(i.applicationId),d=n.headers.get("true-client-ip"),p=Ho.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Gs(n.headers)},y=i.logResponseBody?await Ks(u,e):void 0,O={time:Ws(),status:u.status,headers:Gs(u.headers),body:y},P={request:h,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Kc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(tl,"MoesifInboundPolicy");async function Xs(n,e,t,r){let o=X.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=f.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"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}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.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]}s(Xs,"loadSubscription");async function Ys(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=f.instance,u=X.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});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)}}s(Ys,"consumeSubcriptionQuotas");var nl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Nn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);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}}s(Nn,"validateMeters");function Qs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Qe(n),r=[];for(let o of t)nl.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.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"]}s(Qs,"parseAllowedSubscriptionStatuses");function ea(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(ea,"compareMeters");var qo=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,Tt)}static setMeters(e,t){Nn(t,"setMeters"),ge.set(e,Kt,t)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){Y(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=st(this.options.meterOnStatusCodes),i=ge.get(t,Kt),a={...this.options.meters,...i};Nn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Qs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,H)=>{let _=ge.get(H,Tt);if((this.options.allowRequestsWithoutSubscription??!1)&&!_){H.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 q=ge.get(H,Kt),$={...this.options.meters,...q};if(Nn($,this.policyName),o.includes(P.status)&&_&&$){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${_.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:M}=ea(_.meters,$);if(M&&Object.keys(M).length>0){let V=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Ys(H,_.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.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 Xs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.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.`),x.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`),ge.set(t,Tt,p));let h=ge.get(t,Tt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.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}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Dn(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 r=await fe({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(r.status!==200){try{let i=await r.text();e.log.error("Error getting token from identity provider.",i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(Dn,"getClientCredentialsAccessToken");var Rt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},Mn=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Rt("unknown",`Unknown error. Status: ${c.status}`):new Rt(l.code,l.message)}return c.json()}};function Bt(n,e,t){!n[e]&&t&&(n[e]=t)}s(Bt,"setHeaderIfNotSet");var ta="X-OpenFGA-Client-Method",na="X-OpenFGA-Client-Bulk-Request-Id",Vt=class extends Mn{static{s(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:r={}}=t;return Bt(r,ta,"BatchCheck"),Bt(r,na,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Rt)throw a;return{allowed:void 0,error:a,_request:i}})))}}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:r,object:o,relations:i,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Bt(c,ta,"ListRelations"),Bt(c,na,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,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 ra=Symbol("openfga-authz-context-data"),Pt=class extends pe{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];ge.set(e,ra,r)}constructor(e,t){if(super(e,t),Y(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")Y(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")Y(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")Y(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 Vt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await le(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ge.get(t,ra);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});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),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new W(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await Dn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var oa=["us1","eu1","au1"],Zo=class extends Pt{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!oa.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${oa.join(", ")}.`);let r={...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(r,t),g("policy.inbound.oktafga-authz")}};var rl=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Fo=class extends Pt{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as ol}from"jose";var $o,il=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!$o)try{$o=await ol(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return we(n,e,{issuer:t.authUrl,secret:$o,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ca=Ve(Ge());var sa=Ve(Ge());var ia=(0,sa.debug)("zuplo:policies:RateLimitInboundPolicy"),aa=s(async(n,e,t,r)=>{let o=X.getLogger(e),i=s(($,E)=>{let M={};return(!$||$==="retry-after")&&(M[ht]=E.toString()),x.tooManyRequests(n,e,void 0,M)},"rateLimited"),u=await gt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=ft(r,o),O=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${r}/${c}`,P=await le(r,void 0,t),S=new ie(P,e),H=_n(O,d,h,e.requestId),_;s(async()=>{let $=await H;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;S.put(O,E,$.ttlSeconds),ia(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),_=i(p,$.ttlSeconds)}},"asyncCheck")();let q=await S.get(O);if(q!==void 0&&q>Date.now()){ia(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return i(p,$)}return e.addResponseSendingHook(async $=>_??$),n},"AsyncRateLimitInboundPolicyImpl");var ua=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),sl="strict",la=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??sl)==="async")return aa(n,e,t,r);let i=Date.now(),a=X.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[ht]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await gt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=ft(r,a),H=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${r}/${p}`,_=await _n(H,y,P,e.requestId);return _.count>h?(ua(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(O,_.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;ua(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var jo;function da(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(da,"headersToNameValuePairs");function al(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(al,"queryToNameValueParis");function ul(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(ul,"parseIntOrUndefined");var pa={};async function cl(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return jo||(jo={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?Ye(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ye(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:jo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:da(n.headers),queryString:al(n.query)},response:{status:a.status,statusText:a.statusText,headers:da(a.headers),content:{size:ul(n.headers.get("content-length"))}}}]}}},d=pa[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",O=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),pa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(cl,"ReadmeMetricsInboundPolicy");var ll=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new te(n,{headers:i})},"RemoveHeadersInboundPolicy");var dl=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var pl=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new te(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var ml=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ma=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),gl=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?ma():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ma():n},"RequestSizeLimitInboundPolicy");var It=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Et=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Fn(t,r,o,c.name),p=he.instance.schemaValidator[d],h=p(e[c.name]),y=zo(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ae=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),zo=s(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 ga(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",O,[r],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=$n(n.route.path,e.method,o),u=he.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")}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=zo(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return h}s(ga,"handleBodyValidation");function fa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=It(n),i=Et(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ae(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Le(t.validateHeaders))return u}}s(fa,"handleHeadersValidation");function ha(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}s(ha,"handlePathParameterValidation");function ya(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}s(ya,"handleQueryParameterValidation");var ba=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=ya(e,n,t);if(r!==void 0||(r=ha(e,n,t),r!==void 0)||(r=fa(e,n,t),r!==void 0))return r;let o=await ga(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),fl=ba;var hl=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var yl=s(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var bl=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new te(n,{headers:i})},"SetHeadersInboundPolicy");var wl=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Rl=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new te(i.toString(),n)},"SetQueryParamsInboundPolicy");var Pl=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Il=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),El=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Il(t.sleepInMs),n},"SleepInboundPolicy");var xl=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),Y(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await we(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Tl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),Y(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await le(r,void 0,t),i=new ie(o,e),a=await i.get(r);if(!a){let u=await vl(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function vl(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await fe({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(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(vl,"getAccessToken");var wa="https://accounts.google.com/o/oauth2/token",Bo,Sl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),Y(t,r).required("serviceAccountJson","string"),Bo||(Bo=await xe.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await le(r,void 0,t),a=new ie(i,e),u=await a.get(r);if(!u){let c=await _e({serviceAccount:Bo,audience:wa,payload:o}),l=await dn(wa,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(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Cl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Ol=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vo,Al=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),Y(t,r).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 '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Ol.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Vo||(Vo=await xe.init(t.serviceAccountJson));let i=t.userId;if(!i&&!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?.");i=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?`);i=Ye(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await le(r,void 0,t),u=new ie(a,e),c={uid:i,claims:o},l=await Tn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await _e({serviceAccount:Vo,audience:Cl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await os(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 Go,Ll=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),Y(t,r).required("audience","string").required("serviceAccountJson","string"),Go||(Go=await xe.init(t.serviceAccountJson));let o=await _e({serviceAccount:Go,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ra="https://www.googleapis.com/oauth2/v4/token",Wo,kl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),Y(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Wo||(Wo=await xe.init(t.serviceAccountJson));let o={};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=Qe(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await le(r,void 0,t),a;t.useMemoryCacheOnly?a=new rt(i):a=new ie(i,e);let u=await a.get(r);if(!u){let c=await _e({serviceAccount:Wo,audience:Ra,payload:o}),l=await dn(Ra,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(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var _l=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new W("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Pa=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),o=s((P,S)=>s(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={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:function(_,j){return j},attributeValueProcessor:function(_,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(_,j,q){return _}},H=r(function(_){return Object.assign({},S,_)},"buildOptions");P.buildOptions=H,P.defaultOptions=S}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":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",H=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",_="["+S+"]["+H+"]*",j=new RegExp("^"+_+"$"),q=r(function(E,M){let V=[],G=M.exec(E);for(;G;){let v=[];v.startIndex=M.lastIndex-G[0].length;let T=G.length;for(let U=0;U<T;U++)v.push(G[U]);V.push(v),G=M.exec(E)}return V},"getAllMatches"),$=r(function(E){let M=j.exec(E);return!(M===null||typeof M>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,M,V){if(M){let G=Object.keys(M),v=G.length;for(let T=0;T<v;T++)V==="strict"?E[G[T]]=[M[G[T]]]:E[G[T]]=M[G[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=_}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var H=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(_){this.tagname=_,this.child=[],this[":@"]={}}add(_,j){_==="__proto__"&&(_="#__proto__"),this.child.push({[_]:j})}addChild(_){_.tagname==="__proto__"&&(_.tagname="#__proto__"),_[":@"]&&Object.keys(_[":@"]).length>0?this.child.push({[_.tagname]:_.child,":@":_[":@"]}):this.child.push({[_.tagname]:_.child})}};S.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var H=a();function _(v,T){let U={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let ue=1,K=!1,Q=!1,ve="";for(;T<v.length;T++)if(v[T]==="<"&&!Q){if(K&&$(v,T))T+=7,[entityName,val,T]=j(v,T+1),val.indexOf("&")===-1&&(U[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(v,T))T+=8;else if(K&&M(v,T))T+=8;else if(K&&V(v,T))T+=9;else if(q)Q=!0;else throw new Error("Invalid DOCTYPE");ue++,ve=""}else if(v[T]===">"){if(Q?v[T-1]==="-"&&v[T-2]==="-"&&(Q=!1,ue--):ue--,ue===0)break}else v[T]==="["?K=!0:ve+=v[T];if(ue!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}s(_,"readDocType"),r(_,"readDocType");function j(v,T){let U="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)U+=v[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ue=v[T++],K="";for(;T<v.length&&v[T]!==ue;T++)K+=v[T];return[U,K,T]}s(j,"readEntityExp"),r(j,"readEntityExp");function q(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}s(q,"isComment"),r(q,"isComment");function $(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}s($,"isEntity"),r($,"isEntity");function E(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}s(E,"isElement"),r(E,"isElement");function M(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}s(M,"isAttlist"),r(M,"isAttlist");function V(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),S.exports=_}}),l=o({"../../node_modules/strnum/strnum.js"(P,S){var H=/^[-+]?0x[a-fA-F0-9]+$/,_=/^([\-\+])?(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 j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,M={}){if(M=Object.assign({},j,M),!E||typeof E!="string")return E;let V=E.trim();if(M.skipLike!==void 0&&M.skipLike.test(V))return E;if(M.hex&&H.test(V))return Number.parseInt(V,16);{let G=_.exec(V);if(G){let v=G[1],T=G[2],U=$(G[3]),ue=G[4]||G[6];if(!M.leadingZeros&&T.length>0&&v&&V[2]!==".")return E;if(!M.leadingZeros&&T.length>0&&!v&&V[1]!==".")return E;{let K=Number(V),Q=""+K;return Q.search(/[eE]/)!==-1||ue?M.eNotation?K:E:V.indexOf(".")!==-1?Q==="0"&&U===""||Q===U||v&&Q==="-"+U?K:E:T?U===Q||v+U===Q?K:E:V===Q||V===v+Q?K:E}}else return E}}s(q,"toNumber"),r(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s($,"trimZeros"),r($,"trimZeros"),S.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var H=a(),_=u(),j=c(),q=l(),$=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=M,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ue,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let z=I[A];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function M(R,I,A,z,L,N,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let Z=this.options.tagValueProcessor(I,R,A,L,N);return Z==null?R:typeof Z!=typeof R||Z!==R?Z:this.options.trimValues?ce(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?ce(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(M,"parseTextData"),r(M,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,G),L=z.length,N={};for(let ee=0;ee<L;ee++){let Z=this.resolveNameSpace(z[ee][1]),D=z[ee][4],oe=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ne=this.options.attributeValueProcessor(Z,D,I);ne==null?N[oe]=D:typeof ne!=typeof D||ne!==D?N[oe]=ne:N[oe]=ce(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[oe]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
|
|
62
62
|
`);let I=new _("!xml"),A=I,z="",L="";for(let N=0;N<R.length;N++)if(R[N]==="<")if(R[N+1]==="/"){let Z=b(R,">",N,"Closing Tag is not closed."),D=R.substring(N+2,Z).trim();if(this.options.removeNSPrefix){let Ce=D.indexOf(":");Ce!==-1&&(D=D.substr(Ce+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&(z=this.saveTextToParentTag(z,A,L));let oe=L.substring(L.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ne=0;oe&&this.options.unpairedTags.indexOf(oe)!==-1?(ne=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=L.lastIndexOf("."),L=L.substring(0,ne),A=this.tagsNodeStack.pop(),z="",N=Z}else if(R[N+1]==="?"){let Z=C(R,N,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,A,L),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let D=new _(Z.tagName);D.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(D[":@"]=this.buildAttributesMap(Z.tagExp,L,Z.tagName)),this.addChild(A,D,L)}N=Z.closeIndex+1}else if(R.substr(N+1,3)==="!--"){let Z=b(R,"-->",N+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(N+4,Z-2);z=this.saveTextToParentTag(z,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}N=Z}else if(R.substr(N+1,2)==="!D"){let Z=j(R,N);this.docTypeEntities=Z.entities,N=Z.i}else if(R.substr(N+1,2)==="!["){let Z=b(R,"]]>",N,"CDATA is not closed.")-2,D=R.substring(N+9,Z);z=this.saveTextToParentTag(z,A,L);let oe=this.parseTextData(D,A.tagname,L,!0,!1,!0,!0);oe==null&&(oe=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):A.add(this.options.textNodeName,oe),N=Z+2}else{let Z=C(R,N,this.options.removeNSPrefix),D=Z.tagName,oe=Z.rawTagName,ne=Z.tagExp,Ce=Z.attrExpPresent,ri=Z.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&z&&A.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,A,L,!1));let oi=A;if(oi&&this.options.unpairedTags.indexOf(oi.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),D!==I.tagname&&(L+=L?"."+D:D),this.isItStopNode(this.options.stopNodes,L,D)){let Se="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)N=Z.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)N=Z.closeIndex;else{let Zn=this.readStopNodeData(R,oe,ri+1);if(!Zn)throw new Error(`Unexpected end of ${oe}`);N=Zn.i,Se=Zn.tagContent}let qn=new _(D);D!==ne&&Ce&&(qn[":@"]=this.buildAttributesMap(ne,L,D)),Se&&(Se=this.parseTextData(Se,D,L,!0,Ce,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),qn.add(this.options.textNodeName,Se),this.addChild(A,qn,L)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),L=L.substr(0,L.length-1),ne=D):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Se=new _(D);D!==ne&&Ce&&(Se[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,Se,L),L=L.substr(0,L.lastIndexOf("."))}else{let Se=new _(D);this.tagsNodeStack.push(A),D!==ne&&Ce&&(Se[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,Se,L),A=Se}z="",N=ri}}else z+=R[N];return I.child},"parseXml");function U(R,I,A){let z=this.options.updateTag(I.tagname,A,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}s(U,"addChild"),r(U,"addChild");var ue=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,A,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}s(K,"saveTextToParentTag"),r(K,"saveTextToParentTag");function Q(R,I,A){let z="*."+A;for(let L in R){let N=R[L];if(z===N||I===N)return!0}return!1}s(Q,"isItStopNode"),r(Q,"isItStopNode");function ve(R,I,A=">"){let z,L="";for(let N=I;N<R.length;N++){let ee=R[N];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===A[0])if(A[1]){if(R[N+1]===A[1])return{data:L,index:N}}else return{data:L,index:N};else ee===" "&&(ee=" ");L+=ee}}s(ve,"tagExpWithClosingIndex"),r(ve,"tagExpWithClosingIndex");function b(R,I,A,z){let L=R.indexOf(I,A);if(L===-1)throw new Error(z);return L+I.length-1}s(b,"findClosingIndex"),r(b,"findClosingIndex");function C(R,I,A,z=">"){let L=ve(R,I+1,z);if(!L)return;let N=L.data,ee=L.index,Z=N.search(/\s/),D=N,oe=!0;Z!==-1&&(D=N.substring(0,Z),N=N.substring(Z+1).trimStart());let ne=D;if(A){let Ce=D.indexOf(":");Ce!==-1&&(D=D.substr(Ce+1),oe=D!==L.data.substr(Ce+1))}return{tagName:D,tagExp:N,closeIndex:ee,attrExpPresent:oe,rawTagName:ne}}s(C,"readTagExp"),r(C,"readTagExp");function B(R,I,A){let z=A,L=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let N=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,N).trim()===I&&(L--,L===0))return{tagContent:R.substring(z,A),i:N};A=N}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let N=C(R,A,">");N&&((N&&N.tagName)===I&&N.tagExp[N.tagExp.length-1]!=="/"&&L++,A=N.closeIndex)}}s(B,"readStopNodeData"),r(B,"readStopNodeData");function ce(R,I,A){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,A)}else return H.isExist(R)?R:""}s(ce,"parseValue"),r(ce,"parseValue"),S.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function S($,E){return H($,E)}s(S,"prettify"),r(S,"prettify");function H($,E,M){let V,G={};for(let v=0;v<$.length;v++){let T=$[v],U=_(T),ue="";if(M===void 0?ue=U:ue=M+"."+U,U===E.textNodeName)V===void 0?V=T[U]:V+=""+T[U];else{if(U===void 0)continue;if(T[U]){let K=H(T[U],E,ue),Q=q(K,E);T[":@"]?j(K,T[":@"],ue,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),G[U]!==void 0&&G.hasOwnProperty(U)?(Array.isArray(G[U])||(G[U]=[G[U]]),G[U].push(K)):E.isArray(U,ue,Q)?G[U]=[K]:G[U]=K}}}return typeof V=="string"?V.length>0&&(G[E.textNodeName]=V):V!==void 0&&(G[E.textNodeName]=V),G}s(H,"compress"),r(H,"compress");function _($){let E=Object.keys($);for(let M=0;M<E.length;M++){let V=E[M];if(V!==":@")return V}}s(_,"propName"),r(_,"propName");function j($,E,M,V){if(E){let G=Object.keys(E),v=G.length;for(let T=0;T<v;T++){let U=G[T];V.isArray(U,M+"."+U,!0,!0)?$[U]=[E[U]]:$[U]=E[U]}}}s(j,"assignAttributes"),r(j,"assignAttributes");function q($,E){let{textNodeName:M}=E,V=Object.keys($).length;return!!(V===0||V===1&&($[M]||typeof $[M]=="boolean"||$[M]===0))}s(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=S}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var S=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,C){C=Object.assign({},H,C);let B=[],ce=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let L="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
|
|
63
63
|
`&&b[I]!=="\r";I++)L+=b[I];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),I--),!K(L)){let Z;return L.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+L+"' is an invalid name.",U("InvalidTag",Z,Q(b,I))}let N=M(b,I);if(N===!1)return U("InvalidAttr","Attributes for '"+L+"' have open quote.",Q(b,I));let ee=N.value;if(I=N.index,ee[ee.length-1]==="/"){let Z=I-ee.length;ee=ee.substring(0,ee.length-1);let D=G(ee,C);if(D===!0)ce=!0;else return U(D.err.code,D.err.msg,Q(b,Z+D.err.line))}else if(z)if(N.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",Q(b,A));{let Z=B.pop();if(L!==Z.tagName){let D=Q(b,Z.tagStartPos);return U("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+L+"'.",Q(b,A))}B.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",Q(b,I));else{let Z=G(ee,C);if(Z!==!0)return U(Z.err.code,Z.err.msg,Q(b,I-ee.length+Z.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",Q(b,I));C.unpairedTags.indexOf(L)!==-1||B.push({tagName:L,tagStartPos:A}),ce=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let Z=T(b,I);if(Z==-1)return U("InvalidChar","char '&' is not expected.",Q(b,I));I=Z}else if(R===!0&&!_(b[I]))return U("InvalidXml","Extra text at the end",Q(b,I));b[I]==="<"&&I--}}else{if(_(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",Q(b,I))}if(ce){if(B.length==1)return U("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",Q(b,B[0].tagStartPos));if(B.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function _(b){return b===" "||b===" "||b===`
|
|
64
64
|
`||b==="\r"}s(_,"isWhiteSpace"),r(_,"isWhiteSpace");function j(b,C){let B=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let ce=b.substr(B,C-B);if(C>5&&ce==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",Q(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}s(j,"readPI"),r(j,"readPI");function q(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let B=1;for(C+=8;C<b.length;C++)if(b[C]==="<")B++;else if(b[C]===">"&&(B--,B===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}s(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var $='"',E="'";function M(b,C){let B="",ce="",R=!1;for(;C<b.length;C++){if(b[C]===$||b[C]===E)ce===""?ce=b[C]:ce!==b[C]||(ce="");else if(b[C]===">"&&ce===""){R=!0;break}B+=b[C]}return ce!==""?!1:{value:B,index:C,tagClosed:R}}s(M,"readAttributeStr"),r(M,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(b,C){let B=S.getAllMatches(b,V),ce={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",ve(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",ve(B[R]));if(B[R][3]===void 0&&!C.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",ve(B[R]));let I=B[R][2];if(!ue(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",ve(B[R]));if(!ce.hasOwnProperty(I))ce[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",ve(B[R]))}return!0}s(G,"validateAttributeString"),r(G,"validateAttributeString");function v(b,C){let B=/\d/;for(b[C]==="x"&&(C++,B=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(B))break}return-1}s(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function T(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,v(b,C);let B=0;for(;C<b.length;C++,B++)if(!(b[C].match(/\w/)&&B<20)){if(b[C]===";")break;return-1}return C}s(T,"validateAmpersand"),r(T,"validateAmpersand");function U(b,C,B){return{err:{code:b,msg:C,line:B.line||B,col:B.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function ue(b){return S.isName(b)}s(ue,"validateAttrName"),r(ue,"validateAttrName");function K(b){return S.isName(b)}s(K,"validateTagName"),r(K,"validateTagName");function Q(b,C){let B=b.substring(0,C).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}s(Q,"getLineNumberForPosition"),r(Q,"getLineNumberForPosition");function ve(b){return b.startIndex+b[1].length}s(ve,"getPositionFromMatch"),r(ve,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,S){var{buildOptions:H}=i(),_=d(),{prettify:j}=p(),q=h(),$=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=H(E)}parse(E,M){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(M){M===!0&&(M={});let v=q.validate(E,M);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let V=new _(this.options);V.addExternalEntities(this.externalEntities);let G=V.parseXml(E);return this.options.preserveOrder||G===void 0?G:j(G,this.options)}addEntity(E,M){if(M.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(M==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=M}};S.exports=$}});let O=y();return new O(n)},"getXmlParser");var Ko=class extends $e{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),Y(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?st(e.parseOnStatusCodes):void 0,this.parser=Pa({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var Jo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new W(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Xo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new J(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),wn().waitUntil(this.#e.waitUntilFlushed())}};var Ia=10,Ea=3e4,Yo=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Ea,this.#r=Ia}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Ea,this.#r=Ia}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Nl(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);wn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Nl(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(Nl,"waitUntilTrue");var Gt,Qo=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){if(Gt&&Gt.expiresAt<new Date)return Gt.token;let{authClientId:r,authClientSecret:o,developerApiUrl:i,zuploClientAuthBucketId:a}=f.instance;if(!r||!o)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let u=await Dn({tokenEndpointUrl:`${i}/v1/client-auth/${a}/oauth/token`,clientId:r,clientSecret:o,audience:t?.audience},e);return Gt={token:u.access_token,expiresAt:new Date(u.expires_in*1e3+Date.now()-3e5)},Gt.token}};var ei=["sha-1","sha-256","sha-384","sha-512"],Hn=class{static{s(this,"BaseCryptoBeta")}};var ti=class extends Hn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!ei.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${ei.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Un=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var ni=class extends Un{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=f.instance.runtime.ZUPLO_KV;if(!t)throw new ii("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{ro as AWSLoggingPlugin,uc as AmberfloMeteringInboundPolicy,Eo as AmberfloMeteringPolicy,dc as ApiAuthKeyInboundPolicy,xo as ApiKeyInboundPolicy,go as AuditLogDataStaxProvider,fo as AuditLogPlugin,hc as Auth0JwtInboundPolicy,Cu as AwsLambdaHandlerExtensions,Co as AxiomaticsAuthZInboundPolicy,Xo as BackgroundDispatcher,Yo as BackgroundLoader,yc as BasicAuthInboundPolicy,la as BasicRateLimitInboundPolicy,J as BatchDispatch,Lo as BrownoutInboundPolicy,Cc as CachingInboundPolicy,Oc as ChangeMethodInboundPolicy,Ac as ClearHeadersInboundPolicy,Lc as ClearHeadersOutboundPolicy,kc as ClerkJwtInboundPolicy,_c as CognitoJwtInboundPolicy,Do as ComplexRateLimitInboundPolicy,Fc as CompositeInboundPolicy,m as ConfigurationError,lr as ContentTypes,ge as ContextData,ti as CryptoBeta,$c as CurityPhantomTokenInboundPolicy,Dr as DataDogLoggingPlugin,so as DataDogMetricsPlugin,Wr as DynaTraceLoggingPlugin,lo as DynatraceMetricsPlugin,zc as FirebaseJwtInboundPolicy,Bc as FormDataToJsonInboundPolicy,Vc as GeoFilterInboundPolicy,Ar as GoogleCloudLoggingPlugin,Zr as Handler,x as HttpProblems,tn as HttpStatusCode,pe as InboundPolicy,Gc as JWTScopeValidationInboundPolicy,ni as KeyValueStore,Jr as LokiLoggingPlugin,Zt as LookupResult,ie as MemoryZoneReadThroughCache,Wc as MockApiInboundPolicy,tl as MoesifInboundPolicy,qo as MonetizationInboundPolicy,Zo as OktaFGAAuthZInboundPolicy,rl as OktaJwtInboundPolicy,Fo as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,$e as OutboundPolicy,Je as ProblemResponseFormatter,il as PropelAuthJwtInboundPolicy,la as RateLimitInboundPolicy,cl as ReadmeMetricsInboundPolicy,ll as RemoveHeadersInboundPolicy,dl as RemoveHeadersOutboundPolicy,pl as RemoveQueryParamsInboundPolicy,ml as ReplaceStringOutboundPolicy,gl as RequestSizeLimitInboundPolicy,ba as RequestValidationInboundPolicy,hl as RequireOriginInboundPolicy,Ot as ResponseSendingEvent,At as ResponseSentEvent,Ft as Router,k as RuntimeError,Jt as SYSTEM_LOGGER,fl as SchemaBasedRequestValidation,ke as SemanticAttributes,Jo as ServiceProviderImpl,yl as SetBodyInboundPolicy,bl as SetHeadersInboundPolicy,wl as SetHeadersOutboundPolicy,Rl as SetQueryParamsInboundPolicy,Pl as SetStatusOutboundPolicy,El as SleepInboundPolicy,Ns as StripeMonetizationPlugin,jt as StripeWebhookVerificationInboundPolicy,Qr as SumoLogicLoggingPlugin,xl as SupabaseJwtInboundPolicy,qe as SystemRouteName,vt as TelemetryPlugin,Tl as UpstreamAzureAdServiceAuthInboundPolicy,Sl as UpstreamFirebaseAdminAuthInboundPolicy,Al as UpstreamFirebaseUserAuthInboundPolicy,Ll as UpstreamGcpJwtInboundPolicy,kl as UpstreamGcpServiceAuthInboundPolicy,to as VMWareLogInsightLoggingPlugin,_l as ValidateJsonSchemaInbound,Ko as XmlToJsonOutboundPolicy,xt as ZoneCache,te as ZuploRequest,Qo as ZuploServices,Ou as awsLambdaHandler,Re as environment,Fn as getIdForParameterSchema,Ta as getIdForRefSchema,$n as getIdForRequestBodySchema,xa as getRawOperationDataIdentifierName,pr as httpStatuses,Hu as openApiSpecHandler,qu as redirectHandler,va as sanitizedIdentifierName,dr as serialize,Yc as setMoesifContext,g as trackFeature,Fu as urlForwardHandler,ju as urlRewriteHandler,zu as webSocketHandler,Bu as webSocketPipelineHandler};
|