@zuplo/runtime 6.47.10 → 6.47.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/out/esm/index.js +1 -1
  2. package/package.json +1 -1
package/out/esm/index.js CHANGED
@@ -86,7 +86,7 @@ Signature verification is impossible without access to the original signed mater
86
86
  `+l+`
87
87
  `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new $e(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(wd,"validateComputedSignature");function Rd(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:[]})}i(Rd,"parseHeader");function Pd(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}i(Pd,"secureCompare");async function Id(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=mi[s[u]];return a.join("")}i(Id,"computeHMACSignatureAsync");var mi=new Array(256);for(let n=0;n<mi.length;n++)mi[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var cn=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(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 Ga(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Va(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Va,"isStripeWebhookEvent");var Ed={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o},"getUpcomingInvoice")},Qn=Ed;var gi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Wa="My API Key";async function Ja({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,gi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Wa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:J.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ja,"createConsumer");async function Ka({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,gi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Wa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:J.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new k(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ka,"createConsumerInvite");async function Qa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,gi);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:J.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Qa,"deleteConsumer");async function Ya({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey: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:m}=y.instance;if(!ft(p))throw new Y("No Zuplo JWT token set.");let h=await we({retryDelayMs:5,retries:2,logger:J.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let P=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,C="";try{b=await h.json(),C=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(P,b),new k(`${P} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ya,"createSubscription");async function It({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.getLogger(n)},`${s}/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)}'.`)}i(It,"updateSubscription");async function Et({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.getLogger(n)},`${s}/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]}i(Et,"getSubscription");var ue="Skipping since we're unable to process the webhook event.",et="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Yn(n){return n.replaceAll("_","-")}i(Yn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function fi(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:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:ue,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:ue,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!==y.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:ue,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.`+xe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Ja({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Qn.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:ue,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ka({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:ue,detail:p.message})}if(!c)return x.ok(n,e,{title:ue,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Yn(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let h;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")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Ya({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Qa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ue,detail:p.message})}return x.ok(n,e,{title:et})}i(fi,"onCustomerSubscriptionCreated");async function hi(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:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ue,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!==y.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:ue,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.`+xe});try{let a=await Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await It({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ue,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. `+xe})}return x.ok(n,e,{title:et})}i(hi,"onCustomerSubscriptionDeleted");async function yi(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:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ue,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!==y.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:ue,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.`+xe});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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Yn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ue,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. `+xe})}return x.ok(n,e,{title:et})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Qn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.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 It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ue,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. `+xe})}return x.ok(n,e,{title:et})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await It({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:ue,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. `+xe})}return x.ok(n,e,{title:et})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ue,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."+xe})}i(yi,"onCustomerSubscriptionUpdated");var Xa=class extends xn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(he.ZUPLO_METERING_SERVICE_BUCKET_ID)d=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!xd(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Va(h))return x.ok(c,l,{title:ue,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await fi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await yi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await hi(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ue,detail:`Event '${h.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.`+xe})}},"stripeWebhookHandler"),s=ea({inboundPolicies:[new cn({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new fe({processors:[Pe,s],handler:o,gateway:r}),u=new pe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function xd(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(xd,"isMetricsRegion");var tu=new WeakMap,eu={},bi=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){tu.set(e,t)}};async function Td(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=tu.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=Fe(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)},m=eu[t.apiKey];if(!m){let h=t.apiKey,P=n.headers.get("zm-test-id")??"";m=new K("amberflo-ingest-meter",10,async b=>{try{let C=t.url??"https://app.amberflo.io/ingest",L=await Z.fetch(C,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":P}});L.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${L.status}: ${await L.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),eu[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(Td,"AmberfloMeteringInboundPolicy");async function ct(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("")}i(ct,"sha256");var nu=new Map;async function ie(n,e,t){let r,o=`${n}-${e}`,s=nu.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,nu.set(n,r)),r}i(ie,"getPolicyCacheName");var ru="key-metadata-cache-type";function vd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(vd,"getKeyValue");async function wi(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`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 g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(L=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:L}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=vd(a,o);if(!u||u==="")return s("No key present");let c=await Cd(u),l=await ie(r,void 0,o),d=new re(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!==ru&&J.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},h=new Headers({"content-type":"application/json"});De(h,e.requestId);let P=await we({retryDelayMs:5,retries:2,logger:J.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(P.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(P.status!==200){try{let L=await P.text(),S=JSON.parse(L);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${P.status}`)}let b=await P.json(),C={isValid:!0,typeId:ru,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=C.user,d.put(c,C,o.cacheTtlSeconds),n}i(wi,"ApiKeyInboundPolicy");async function Cd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Cd,"hashValue");var Sd=wi;var ou=Symbol("aserto-authz-resource-context"),Ri=class extends ae{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){oe.set(e,ou,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new g(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await ie(this.policyName,void 0,this.options);this.cache=new re(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),x.unauthorized(e,t);let o=oe.get(t,ou),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Fe(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await Z.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):x.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),x.internalServerError(e,t)}}};import{createRemoteJWKSet as Od,jwtVerify as su}from"jose";import{createLocalJWKSet as Ad}from"jose";var Pi=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Ii&&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",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Ad(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ei("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new xt("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 xt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function iu(n,e,t){let r=new Pi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(iu,"createRemoteJWKSet");var xt=class extends k{static{i(this,"JWKSError")}},Ii=class extends xt{static{i(this,"JWKSNoMatchingKey")}},Ei=class extends xt{static{i(this,"JWKSTimeout")}};var Xn={},kd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!Xn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ie(n,void 0,r),u=new re(a,e);Xn[r.jwkUrl]=iu(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Xn[r.jwkUrl]=Od(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await su(t,Xn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Ld=i(async(n,e)=>{let t;if(e.secret===void 0)throw new g("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await su(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Ee=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?kd(r,e):Ld,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let h=s.substring(a.length);if(!h||h.length===0)return u("No bearer token on authorization header");try{return await c(h,t)}catch(P){let b=new URL(n.url);return"code"in P&&P.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,P):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,P),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var _d=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),Ee(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var au=new Map;function Nd(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let s=n.substring(o,t);for(e.push(s),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}i(Nd,"parsePropertyPath");function er(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=au.get(r);o||(o=Nd(r),au.set(r,o));let s=e;for(let a of o){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(er,"evaluateAuthzenProp");var uu=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),xi=class n extends ae{static{i(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),W(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new g(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new g(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new g(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new g(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new g(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new g(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
88
88
  ${r}`)}}async handler(e,t){let r=this.options.throwOnError!==!1;try{await this.#o(t);let o=this.options.debug===!0,s={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:t};s.action?.name!==void 0&&(s.action.name=er(s.action.name,a)),s.subject?.id!==void 0&&(s.subject.id=er(s.subject.id,a)),s.resource?.id!==void 0&&(s.resource.id=er(s.resource.id,a)),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,s);let u=n.getAuthorizationPayload(t);u&&Object.assign(s,u),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:u,final:s}),this.#n(t,!s.subject?.type||!s.subject?.id,"Missing required subject type or id"),this.#n(t,!s.resource?.type||!s.resource?.id,"Missing required resource type or id"),this.#n(t,!s.action,"Missing required action");let c={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(c.authorization=this.options.authorizerAuthorizationHeader);let l=await fetch(this.#e,{method:"POST",body:JSON.stringify(s),headers:c});if(!l.ok){let p=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
89
- ${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#r(e,t,r){return x.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ie(this.policyName,void 0,this.options);this.#t=new re(t,e)}}static setAuthorizationPayload(e,t){oe.set(e,uu,t)}static getAuthorizationPayload(e){return oe.get(e,uu)}};var tr=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Ti=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new tr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value: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(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),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 s=this.options[e];if(s){let a=[];s.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 Dd=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),P=t.accounts.find(b=>b.username===m&&b.password===h);return P||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function nr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(nr,"extractDateElements");function cu(n,e){return new Date(n,e+1,0).getDate()}i(cu,"getDaysInMonth");function vi(n,e){return n<=e?e-n:6-n+e+1}i(vi,"getDaysBetweenWeekdays");var rr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=cu(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?vi(d,p):vi(p,d);l=e==="next"?o+m:o-m,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=nr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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 s=0;s<e;s++)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=nr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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 s=0;s<e;s++)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:s,month:a,weekday:u}=nr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Md={min:0,max:59},qd={min:0,max:59},Ud={min:0,max:23},Hd={min:1,max:31},$d={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"}},Zd={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Fd={"@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 lt(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=>{lt(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function Ci(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Fd[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new rr({seconds:lt(t,Md),minutes:lt(r,qd),hours:lt(o,Ud),days:lt(s,Hd),months:new Set(Array.from(lt(a,$d)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Zd)).map(c=>c%7))})}i(Ci,"parseCronExpression");var Si=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`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=[Ci(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ci(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=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(s,e,t)}return e}};var jd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function zd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(zd,"digestMessage");var Bd=i(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 zd(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Gd(n,e,t,r){f("policy.inbound.caching");let o=await ie(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Bd(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);jd.forEach(P=>h.headers.delete(P)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Gd,"CachingInboundPolicy");var Vd=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Wd=i(async(n,e,t)=>{f("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 ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Jd=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Kd=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Ee(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Qd=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Ee(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 or=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ai=class extends or{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Oi=class extends or{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Yd(n,e){if(Gs(n))throw new Ai(e)}i(Yd,"throwIfUndefinedOrNull");function lu(n,e){if(Yd(n,e),!Te(n))throw new Oi(e,"string")}i(lu,"throwIfNotString");var ki=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Xd=500,Li=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){lu(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Xd);let a,u=new Headers({"content-type":"application/json"});De(u,o);try{a=await Z.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new Y("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Tt;function tt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(Tt)return Tt;if(!r)return e.info("Using in-memory rate limit client for local development."),Tt=new ki,Tt;if(!Te(t))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Tt=new Li(t),Tt}i(tt,"getRateLimitClient");var ep=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:op(e,"RateLimitInboundPolicy",n),user:np,ip:tp,all:rp}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var tp=i(async n=>({key:`ip-${ep(n)}`}),"getIP"),np=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),rp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function op(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${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 g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(op,"wrapUserFunction");var Ct="Retry-After";var du=be("zuplo:policies:ComplexRateLimitInboundPolicy"),_i=Symbol("complex-rate-limit-counters"),Ni=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,_i)??{};Object.assign(r,t),oe.set(e,_i,t)}static getIncrements(e){return oe.get(e,_i)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`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=J.getLogger(t),s=tt(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ct]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await vt(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);du(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let L=Object.entries(p).map(([H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${H}`,ttlSeconds:m,increment:C[H]??0})),S=s.multiIncrement(L,t.requestId);t.waitUntil(S),await S}catch(C){a(C.message,C)}});let h=Object.entries(p).map(([C,L])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:m,limit:L})),P=await s.multiCount(h,t.requestId);return ip(P,h).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;du(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function ip(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(ip,"findOverLimits");var sp=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ye.instance,s=Wt(t.policies,o?.routeData.policies);return oo(s)(n,e)},"CompositeInboundPolicy");var ap=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ye.instance,a=Jt(r.policies,s?.routeData.policies);return io(a)(n,e,t)},"CompositeOutboundPolicy");var up=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=cp(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),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 cp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(cp,"getToken");var lp=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Ee(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 dp=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var St="__unknown__",pp=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Ot(t.allow?.countries,"allow.countries",r),regionCodes:Ot(t.allow?.regionCodes,"allow.regionCode",r),asns:Ot(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Ot(t.block?.countries,"block.countries",r),regionCodes:Ot(t.block?.regionCodes,"block.regionCode",r),asns:Ot(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??St,a=e.incomingRequestProperties.regionCode?.toLowerCase()??St,u=e.incomingRequestProperties.asn?.toString()??St,c=o.ignoreUnknown&&s===St,l=o.ignoreUnknown&&a===St,d=o.ignoreUnknown&&u===St,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return At(n,e,r,s,a,u);let P=o.block.countries,b=o.block.regionCodes,C=o.block.asns;return P.length>0&&P.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?At(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function At(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(At,"blockedResponse");function Ot(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 g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ot,"toLowerStringArray");var mp=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var gp=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Di(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Di(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 pu(a[u])}else return a.length>0?pu(a[0]):Di(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 pu(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(pu,"generateResponse");var Di=i((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 fp="Incoming",hp={logRequestBody:!0,logResponseBody:!0};function mu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(mu,"headersToObject");function gu(){return new Date().toISOString()}i(gu,"timestamp");var Mi=new WeakMap,yp={};function bp(n,e){let t=Mi.get(n);t||(t=yp);let r=Object.assign({...t},e);Mi.set(n,r)}i(bp,"setMoesifContext");async function fu(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}i(fu,"readBody");var wp={},qi;function hu(){if(!qi)throw new k("Invalid State - no _lastLogger");return qi}i(hu,"getLastLogger");function Rp(n){let e=wp[n];return e||(e=new K("moesif-inbound",100,async t=>{let r=JSON.stringify(t);hu().debug("posting",r);let o=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||hu().error({status:o.status,body:await o.text()})})),e}i(Rp,"getDispatcher");async function Pp(n,e,t,r){f("policy.inbound.moesif-analytics"),qi=e.log;let o=gu(),s=Object.assign(hp,t);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await fu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Rp(s.applicationId),d=n.headers.get("true-client-ip"),p=Mi.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:mu(n.headers)},h=s.logResponseBody?await fu(u,e):void 0,P={time:gu(),status:u.status,headers:mu(u.headers),body:h},b={request:m,response:P,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:fp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(Pp,"MoesifInboundPolicy");async function yu(n,e,t,r){let o=J.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=y.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),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]}i(yu,"loadSubscription");async function bu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=y.instance,u=J.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(bu,"consumeSubcriptionQuotas");var Ip=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ir(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 g(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 g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(ir,"validateMeters");function wu(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=je(n),r=[];for(let o of t)Ip.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(wu,"parseAllowedSubscriptionStatuses");function Ru(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}}i(Ru,"compareMeters");var Ui=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,Zt)}static setMeters(e,t){ir(t,"setMeters");let r=oe.get(e,Ft)??{};Object.assign(r,t),oe.set(e,Ft,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),s=oe.get(t,Ft),a={...this.options.meters,...s};ir(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=wu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,C,L)=>{let S=oe.get(L,Zt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let F=oe.get(L,Ft),q={...this.options.meters,...F};if(ir(q,this.policyName),o.includes(b.status)&&S&&q){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify(q)} on response status '${b.status}'`);let{metersInSubscription:A,metersNotInSubscription:$}=Ru(S.meters,q);if($&&Object.keys($).length>0){let V=Object.keys($);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await bu(L,S.id,this.policyName,this.options.bucketId,A)}});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(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await yu(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`),oe.set(t,Zt,p));let m=oe.get(t,Zt);if(!m)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(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let P=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(P.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${P.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${P.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function sr(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 we({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 s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}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.")}i(sr,"getClientCredentialsAccessToken");var kt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},ar=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new g("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 s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new kt("unknown",`Unknown error. Status: ${c.status}`):new kt(l.code,l.message)}return c.json()}};function ln(n,e,t){!n[e]&&t&&(n[e]=t)}i(ln,"setHeaderIfNotSet");var Pu="X-OpenFGA-Client-Method",Iu="X-OpenFGA-Client-Bulk-Request-Id",dn=class extends ar{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return ln(r,Pu,"BatchCheck"),ln(r,Iu,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof kt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(ln(c,Pu,"ListRelations"),ln(c,Iu,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user: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 Eu=Symbol("openfga-authz-context-data"),Lt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,Eu,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${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 dn({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,Eu);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),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 Y(`${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 s=await sr({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var xu=["us1","eu1","au1"],Hi=class extends Lt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!xu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${xu.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),f("policy.inbound.oktafga-authz")}};var Ep=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Ee(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var $i=class extends Lt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as xp}from"jose";var Zi,Tp=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!Zi)try{Zi=await xp(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Ee(n,e,{issuer:t.authUrl,secret:Zi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Fi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Tu="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ji=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=J.getLogger(t);try{let s=vp(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Cp(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=tt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let P=[],b="";if(Object.entries(h).forEach(([C,L])=>{r&&(b+=`${C} - allowed: ${L} value: ${m.meters[C]??0}
89
+ ${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#r(e,t,r){return x.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ie(this.policyName,void 0,this.options);this.#t=new re(t,e)}}static setAuthorizationPayload(e,t){oe.set(e,uu,t)}static getAuthorizationPayload(e){return oe.get(e,uu)}};var tr=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Ti=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new tr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value: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(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),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 s=this.options[e];if(s){let a=[];s.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 Dd=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),P=t.accounts.find(b=>b.username===m&&b.password===h);return P||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function nr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(nr,"extractDateElements");function cu(n,e){return new Date(n,e+1,0).getDate()}i(cu,"getDaysInMonth");function vi(n,e){return n<=e?e-n:6-n+e+1}i(vi,"getDaysBetweenWeekdays");var rr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=cu(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?vi(d,p):vi(p,d);l=e==="next"?o+m:o-m,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=nr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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 s=0;s<e;s++)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=nr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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 s=0;s<e;s++)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:s,month:a,weekday:u}=nr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Md={min:0,max:59},qd={min:0,max:59},Ud={min:0,max:23},Hd={min:1,max:31},$d={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"}},Zd={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Fd={"@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 lt(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=>{lt(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function Ci(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Fd[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new rr({seconds:lt(t,Md),minutes:lt(r,qd),hours:lt(o,Ud),days:lt(s,Hd),months:new Set(Array.from(lt(a,$d)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Zd)).map(c=>c%7))})}i(Ci,"parseCronExpression");var Si=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`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=[Ci(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ci(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=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(s,e,t)}return e}};var jd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function zd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(zd,"digestMessage");var Bd=i(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 zd(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Gd(n,e,t,r){f("policy.inbound.caching");let o=await ie(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Bd(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);jd.forEach(P=>h.headers.delete(P)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Gd,"CachingInboundPolicy");var Vd=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Wd=i(async(n,e,t)=>{f("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 ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Jd=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Kd=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Ee(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Qd=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Ee(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 or=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ai=class extends or{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Oi=class extends or{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Yd(n,e){if(Gs(n))throw new Ai(e)}i(Yd,"throwIfUndefinedOrNull");function lu(n,e){if(Yd(n,e),!Te(n))throw new Oi(e,"string")}i(lu,"throwIfNotString");var ki=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Xd=500,Li=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){lu(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Xd);let a,u=new Headers({"content-type":"application/json"});De(u,o);try{a=await Z.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new Y("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Tt;function tt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(Tt)return Tt;if(!r)return e.info("Using in-memory rate limit client for local development."),Tt=new ki,Tt;if(!Te(t))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Tt=new Li(t),Tt}i(tt,"getRateLimitClient");var ep=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:op(e,"RateLimitInboundPolicy",n),user:np,ip:tp,all:rp}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var tp=i(async n=>({key:`ip-${ep(n)}`}),"getIP"),np=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),rp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function op(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${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 g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(op,"wrapUserFunction");var Ct="Retry-After";var du=be("zuplo:policies:ComplexRateLimitInboundPolicy"),_i=Symbol("complex-rate-limit-counters"),Ni=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,_i)??{};Object.assign(r,t),oe.set(e,_i,t)}static getIncrements(e){return oe.get(e,_i)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`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=J.getLogger(t),s=tt(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ct]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await vt(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);du(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let L=Object.entries(p).map(([H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${H}`,ttlSeconds:m,increment:C[H]??0})),S=s.multiIncrement(L,t.requestId);t.waitUntil(S),await S}catch(C){a(C.message,C)}});let h=Object.entries(p).map(([C,L])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:m,limit:L})),P=await s.multiCount(h,t.requestId);return ip(P,h).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;du(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function ip(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(ip,"findOverLimits");var sp=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ye.instance,s=Wt(t.policies,o?.routeData.policies);return oo(s)(n,e)},"CompositeInboundPolicy");var ap=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ye.instance,a=Jt(r.policies,s?.routeData.policies);return io(a)(n,e,t)},"CompositeOutboundPolicy");var up=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=cp(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),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 cp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(cp,"getToken");var lp=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Ee(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 dp=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var St="__unknown__",pp=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Ot(t.allow?.countries,"allow.countries",r),regionCodes:Ot(t.allow?.regionCodes,"allow.regionCode",r),asns:Ot(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Ot(t.block?.countries,"block.countries",r),regionCodes:Ot(t.block?.regionCodes,"block.regionCode",r),asns:Ot(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??St,a=e.incomingRequestProperties.regionCode?.toLowerCase()??St,u=e.incomingRequestProperties.asn?.toString()??St,c=o.ignoreUnknown&&s===St,l=o.ignoreUnknown&&a===St,d=o.ignoreUnknown&&u===St,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return At(n,e,r,s,a,u);let P=o.block.countries,b=o.block.regionCodes,C=o.block.asns;return P.length>0&&P.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?At(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function At(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(At,"blockedResponse");function Ot(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 g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ot,"toLowerStringArray");var mp=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var gp=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Di(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Di(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 pu(a[u])}else return a.length>0?pu(a[0]):Di(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 pu(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(pu,"generateResponse");var Di=i((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 fp="Incoming",hp={logRequestBody:!0,logResponseBody:!0};function mu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(mu,"headersToObject");function gu(){return new Date().toISOString()}i(gu,"timestamp");var Mi=new WeakMap,yp={};function bp(n,e){let t=Mi.get(n);t||(t=yp);let r=Object.assign({...t},e);Mi.set(n,r)}i(bp,"setMoesifContext");async function fu(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}i(fu,"readBody");var wp={},qi;function hu(){if(!qi)throw new k("Invalid State - no _lastLogger");return qi}i(hu,"getLastLogger");function Rp(n){let e=wp[n];return e||(e=new K("moesif-inbound",100,async t=>{let r=JSON.stringify(t);hu().debug("posting",r);let o=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||hu().error({status:o.status,body:await o.text()})})),e}i(Rp,"getDispatcher");async function Pp(n,e,t,r){f("policy.inbound.moesif-analytics"),qi=e.log;let o=gu(),s=Object.assign(hp,t);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await fu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Rp(s.applicationId),d=n.headers.get("true-client-ip"),p=Mi.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:mu(n.headers)},h=s.logResponseBody?await fu(u,e):void 0,P={time:gu(),status:u.status,headers:mu(u.headers),body:h},b={request:m,response:P,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:fp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(Pp,"MoesifInboundPolicy");async function yu(n,e,t,r){let o=J.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=y.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),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]}i(yu,"loadSubscription");async function bu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=y.instance,u=J.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(bu,"consumeSubcriptionQuotas");var Ip=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ir(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 g(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 g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(ir,"validateMeters");function wu(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=je(n),r=[];for(let o of t)Ip.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(wu,"parseAllowedSubscriptionStatuses");function Ru(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}}i(Ru,"compareMeters");var Ui=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,Zt)}static setMeters(e,t){ir(t,"setMeters");let r=oe.get(e,Ft)??{};Object.assign(r,t),oe.set(e,Ft,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),s=oe.get(t,Ft),a={...this.options.meters,...s};ir(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=wu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,C,L)=>{let S=oe.get(L,Zt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let F=oe.get(L,Ft),q={...this.options.meters,...F};if(ir(q,this.policyName),o.includes(b.status)&&S&&q){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify(q)} on response status '${b.status}'`);let{metersInSubscription:A,metersNotInSubscription:$}=Ru(S.meters,q);if($&&Object.keys($).length>0){let V=Object.keys($);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await bu(L,S.id,this.policyName,this.options.bucketId,A)}});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(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await yu(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`),oe.set(t,Zt,p));let m=oe.get(t,Zt);if(!m)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(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let P=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(P.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${P.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${P.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function sr(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 we({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 s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}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.")}i(sr,"getClientCredentialsAccessToken");var kt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},ar=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new g("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 s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new kt("unknown",`Unknown error. Status: ${c.status}`):new kt(l.code,l.message)}return c.json()}};function ln(n,e,t){!n[e]&&t&&(n[e]=t)}i(ln,"setHeaderIfNotSet");var Pu="X-OpenFGA-Client-Method",Iu="X-OpenFGA-Client-Bulk-Request-Id",dn=class extends ar{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return ln(r,Pu,"BatchCheck"),ln(r,Iu,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof kt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(ln(c,Pu,"ListRelations"),ln(c,Iu,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user: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 Eu=Symbol("openfga-authz-context-data"),Lt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,Eu,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.method' 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 dn({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,Eu);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),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 Y(`${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 s=await sr({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var xu=["us1","eu1","au1"],Hi=class extends Lt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!xu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${xu.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),f("policy.inbound.oktafga-authz")}};var Ep=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Ee(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var $i=class extends Lt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as xp}from"jose";var Zi,Tp=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!Zi)try{Zi=await xp(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Ee(n,e,{issuer:t.authUrl,secret:Zi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Fi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Tu="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ji=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=J.getLogger(t);try{let s=vp(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Cp(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=tt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let P=[],b="";if(Object.entries(h).forEach(([C,L])=>{r&&(b+=`${C} - allowed: ${L} value: ${m.meters[C]??0}
90
90
  `),(m.meters[C]??0)>=L&&P.push(C)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),P.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${P.join(", ")}'`});t.addResponseSendingFinalHook(async(C,L,S)=>{if(r&&S.log.debug(`QuotaInboundPolicy: backend response - ${C.status}: ${C.statusText}`),!s.quotaOnStatusCodes.includes(C.status))return;let H=oe.get(S,Fi),F={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:H};r&&S.log.debug("QuotaInboundPolicy: setQuotaDetails",F);let q=p.setQuota(d,F,S.requestId);S.waitUntil(q)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=oe.get(e,Fi)??{};Object.assign(r,t),oe.set(e,Fi,r)}static getUsage(e,t){let r=oe.get(e,`${Tu}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){oe.set(e,`${Tu}-${t}`,r)}};function vp(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:We(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(vp,"validateAndParseOptions");function Cp(n,e){return encodeURIComponent(`${e}-${n}`)}i(Cp,"processKey");var vu=be("zuplo:policies:RateLimitInboundPolicy"),Cu=i(async(n,e,t,r)=>{let o=J.getLogger(e),s=i((q,A)=>{let $={};return(!q||q==="retry-after")&&($[Ct]=A.toString()),x.tooManyRequests(n,e,void 0,$)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=tt(r,o),P=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,b=await ie(r,void 0,t),C=new re(b,e),L=m.getCountAndUpdateExpiry(P,d,e.requestId),S;i(async()=>{let q=await L;if(q.count>l){let A=Date.now()+q.ttlSeconds*1e3;C.put(P,A,q.ttlSeconds),vu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${P}' (async mode)`),S=s(p,q.ttlSeconds)}},"asyncCheck")();let F=await C.get(P);if(F!==void 0&&F>Date.now()){vu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${P}' (async mode)`);let q=Math.round((F-Date.now())/1e3);return s(p,q)}return e.addResponseSendingHook(async q=>S??q),n},"AsyncRateLimitInboundPolicyImpl");function zi(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}i(zi,"convertToNumber");var Su=be("zuplo:policies:RateLimitInboundPolicy"),Sp="strict",Au=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Sp)==="async")return Cu(n,e,t,r);let s=Date.now(),a=J.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Ct]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,m=zi(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=zi(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),P=t.headerMode??"retry-after",b=tt(r,a),L=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,S=await b.getCountAndUpdateExpiry(L,h,e.requestId);return S.count>m?(Su(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${L}' (strict mode)`),c(P,S.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Su(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Bi;function Ou(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ou,"headersToNameValuePairs");function Ap(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Ap,"queryToNameValueParis");function Op(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Op,"parseIntOrUndefined");var ku={};async function kp(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return Bi||(Bi={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Fe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Fe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Bi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ou(n.headers),queryString:Ap(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ou(a.headers),content:{size:Op(n.headers.get("content-length"))}}}]}}},d=ku[t.apiKey];if(!d){let p=t.apiKey;d=new K("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",P=await Z.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});P.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${P.status}: '${await P.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),ku[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(kp,"ReadmeMetricsInboundPolicy");var Lp=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new ee(n,{headers:s})},"RemoveHeadersInboundPolicy");var _p=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Np=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new ee(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Dp=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Lu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Mp=i(async(n,e,t)=>{f("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"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Lu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Lu():n},"RequestSizeLimitInboundPolicy");var _t=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Nt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=dr(t,r,o,c.name),p=ye.instance.schemaValidator[d],m=p(e[c.name]),h=Gi(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),_e=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Gi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function _u(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let P=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=x.badRequest(e,n,{detail:`${P}, see errors property for more details`,errors:`${h}`});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",P,[r],h),Ne(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,P=x.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?P:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=pr(n.route.path,e.method,o),u=ye.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?P:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Gi(l),m=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return m}i(_u,"handleBodyValidation");function Nu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=_t(n),s=Nt(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(_e(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Nu,"handleHeadersValidation");function Du(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Du,"handlePathParameterValidation");function Mu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(Mu,"handleQueryParameterValidation");var qu=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=Mu(e,n,t);if(r!==void 0||(r=Du(e,n,t),r!==void 0)||(r=Nu(e,n,t),r!==void 0))return r;let o=await _u(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),qp=qu;var Up=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Hp=i(async(n,e,t)=>(f("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var $p=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new ee(n,{headers:s})},"SetHeadersInboundPolicy");var Zp=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Fp=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new ee(s.toString(),n)},"SetQueryParamsInboundPolicy");var jp=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new g(`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 zp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Bp=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await zp(t.sleepInMs),n},"SleepInboundPolicy");var Gp=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Ee(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof ee))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${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(", ")}`}):s},"SupabaseJwtInboundPolicy");var Vp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ie(r,void 0,t),s=new re(o,e),a=await s.get(r);if(!a){let u=await Wp(t,e);s.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 Wp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}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.")}i(Wp,"getAccessToken");var Uu="https://accounts.google.com/o/oauth2/token",Vi,Jp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),Vi||(Vi=await Ie.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(" ")},s=await ie(r,void 0,t),a=new re(s,e),u=await a.get(r);if(!u){let c=await Oe({serviceAccount:Vi,audience:Uu,payload:o}),l=await yt(Uu,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 Kp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Qp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Wi,Yp=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`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(Qp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Wi||(Wi=await Ie.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Fe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ie(r,void 0,t),u=new re(a,e),c={uid:s,claims:o},l=await ct(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Oe({serviceAccount:Wi,audience:Kp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await fa(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var pn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ie("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=y.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await sr({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Hu="service-account-id-token",Ji=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Me(this.cacheName):r=new re(this.cacheName,t);let o=await r.get(Hu);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await pn.getIDToken(t,{audience:s}),u=await ma(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await ga({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(Hu,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ki,Xp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Ki||(Ki=await Ie.init(t.serviceAccountJson));let o=await Oe({serviceAccount:Ki,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var $u="https://www.googleapis.com/oauth2/v4/token",Qi,Zu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qi||(Qi=await Ie.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=je(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ie(r,void 0,t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e);let u=await a.get(r);if(!u){let c=await Oe({serviceAccount:Qi,audience:$u,payload:o}),l=await yt($u,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},"UpstreamGcpServiceAuthInboundPolicyV1");var Fu="https://www.googleapis.com/oauth2/v4/token",Yi,ju=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let s=await ie(r,"v2",t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e),Re.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let P=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;J.getLogger(m).error(P),m.log.error(P),await a.delete(r)}});let c=await a.get(r);return c&&c.expirationTime-o<new Date().getTime()&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),c=void 0),c&&c.audience!==t.audience&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${c.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),c=void 0),c||(c=await l()),n.headers.set("Authorization",`Bearer ${c.token}`),n;async function l(){Yi||(Yi=await Ie.init(t.serviceAccountJson));let d={};if(t.scopes)try{let C=je(t.scopes);d.scope=C.join(" ")}catch(C){throw C instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${C.message}`):C}t.audience&&(d.target_audience=`${t.audience}`);let p=await Oe({serviceAccount:Yi,audience:Fu,payload:d}),m=await yt(Fu,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,P=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");c={token:m.id_token,expirationTime:P,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");c={token:m.access_token,expirationTime:P,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,c,b),c}i(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var em=i(async(n,e,t,r)=>t.version===2?await ju(n,e,t,r):await Zu(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var tm=i(async(n,e,t)=>{f("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.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new Y("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 zu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,C)=>e(b,"name",{value:C,configurable:!0}),"__name"),o=i((b,C)=>i(function(){return C||(0,b[t(b)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(S,H){return H},"tagValueProcessor"),attributeValueProcessor:i(function(S,H){return H},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(S,H,F){return S},"updateTag")},L=r(function(S){return Object.assign({},C,S)},"buildOptions");b.buildOptions=L,b.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var C=":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",L=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S="["+C+"]["+L+"]*",H=new RegExp("^"+S+"$"),F=r(function(A,$){let V=[],j=$.exec(A);for(;j;){let T=[];T.startIndex=$.lastIndex-j[0].length;let E=j.length;for(let M=0;M<E;M++)T.push(j[M]);V.push(T),j=$.exec(A)}return V},"getAllMatches"),q=r(function(A){let $=H.exec(A);return!($===null||typeof $>"u")},"isName");b.isExist=function(A){return typeof A<"u"},b.isEmptyObject=function(A){return Object.keys(A).length===0},b.merge=function(A,$,V){if($){let j=Object.keys($),T=j.length;for(let E=0;E<T;E++)V==="strict"?A[j[E]]=[$[j[E]]]:A[j[E]]=$[j[E]]}},b.getValue=function(A){return b.isExist(A)?A:""},b.isName=q,b.getAllMatches=F,b.nameRegexp=S}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,C){"use strict";var L=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(S){this.tagname=S,this.child=[],this[":@"]={}}add(S,H){S==="__proto__"&&(S="#__proto__"),this.child.push({[S]:H})}addChild(S){S.tagname==="__proto__"&&(S.tagname="#__proto__"),S[":@"]&&Object.keys(S[":@"]).length>0?this.child.push({[S.tagname]:S.child,":@":S[":@"]}):this.child.push({[S.tagname]:S.child})}};C.exports=L}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,C){var L=a();function S(T,E){let M={};if(T[E+3]==="O"&&T[E+4]==="C"&&T[E+5]==="T"&&T[E+6]==="Y"&&T[E+7]==="P"&&T[E+8]==="E"){E=E+9;let ce=1,X=!1,te=!1,Se="";for(;E<T.length;E++)if(T[E]==="<"&&!te){if(X&&q(T,E))E+=7,[entityName,val,E]=H(T,E+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&A(T,E))E+=8;else if(X&&$(T,E))E+=8;else if(X&&V(T,E))E+=9;else if(F)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(T[E]===">"){if(te?T[E-1]==="-"&&T[E-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else T[E]==="["?X=!0:Se+=T[E];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:E}}i(S,"readDocType"),r(S,"readDocType");function H(T,E){let M="";for(;E<T.length&&T[E]!=="'"&&T[E]!=='"';E++)M+=T[E];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=T[E++],X="";for(;E<T.length&&T[E]!==ce;E++)X+=T[E];return[M,X,E]}i(H,"readEntityExp"),r(H,"readEntityExp");function F(T,E){return T[E+1]==="!"&&T[E+2]==="-"&&T[E+3]==="-"}i(F,"isComment"),r(F,"isComment");function q(T,E){return T[E+1]==="!"&&T[E+2]==="E"&&T[E+3]==="N"&&T[E+4]==="T"&&T[E+5]==="I"&&T[E+6]==="T"&&T[E+7]==="Y"}i(q,"isEntity"),r(q,"isEntity");function A(T,E){return T[E+1]==="!"&&T[E+2]==="E"&&T[E+3]==="L"&&T[E+4]==="E"&&T[E+5]==="M"&&T[E+6]==="E"&&T[E+7]==="N"&&T[E+8]==="T"}i(A,"isElement"),r(A,"isElement");function $(T,E){return T[E+1]==="!"&&T[E+2]==="A"&&T[E+3]==="T"&&T[E+4]==="T"&&T[E+5]==="L"&&T[E+6]==="I"&&T[E+7]==="S"&&T[E+8]==="T"}i($,"isAttlist"),r($,"isAttlist");function V(T,E){return T[E+1]==="!"&&T[E+2]==="N"&&T[E+3]==="O"&&T[E+4]==="T"&&T[E+5]==="A"&&T[E+6]==="T"&&T[E+7]==="I"&&T[E+8]==="O"&&T[E+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function j(T){if(L.isName(T))return T;throw new Error(`Invalid entity name ${T}`)}i(j,"validateEntityName"),r(j,"validateEntityName"),C.exports=S}}),l=o({"../../node_modules/strnum/strnum.js"(b,C){var L=/^[-+]?0x[a-fA-F0-9]+$/,S=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var H={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function F(A,$={}){if($=Object.assign({},H,$),!A||typeof A!="string")return A;let V=A.trim();if($.skipLike!==void 0&&$.skipLike.test(V))return A;if($.hex&&L.test(V))return Number.parseInt(V,16);{let j=S.exec(V);if(j){let T=j[1],E=j[2],M=q(j[3]),ce=j[4]||j[6];if(!$.leadingZeros&&E.length>0&&T&&V[2]!==".")return A;if(!$.leadingZeros&&E.length>0&&!T&&V[1]!==".")return A;{let X=Number(V),te=""+X;return te.search(/[eE]/)!==-1||ce?$.eNotation?X:A:V.indexOf(".")!==-1?te==="0"&&M===""||te===M||T&&te==="-"+M?X:A:E?M===te||T+M===te?X:A:V===te||V===T+te?X:A}}else return A}}i(F,"toNumber"),r(F,"toNumber");function q(A){return A&&A.indexOf(".")!==-1&&(A=A.replace(/0+$/,""),A==="."?A="0":A[0]==="."?A="0"+A:A[A.length-1]==="."&&(A=A.substr(0,A.length-1))),A}i(q,"trimZeros"),r(q,"trimZeros"),C.exports=F}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,C){"use strict";var L=a(),S=u(),H=c(),F=l(),q=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(I){this.options=I,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((v,_)=>String.fromCharCode(Number.parseInt(_,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((v,_)=>String.fromCharCode(Number.parseInt(_,16)),"val")}},this.addExternalEntities=A,this.parseXml=E,this.parseTextData=$,this.resolveNameSpace=V,this.buildAttributesMap=T,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=M}};function A(I){let v=Object.keys(I);for(let _=0;_<v.length;_++){let B=v[_];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:I[B]}}}i(A,"addExternalEntities"),r(A,"addExternalEntities");function $(I,v,_,B,N,D,ne){if(I!==void 0&&(this.options.trimValues&&!B&&(I=I.trim()),I.length>0)){ne||(I=this.replaceEntitiesValue(I));let z=this.options.tagValueProcessor(v,I,_,N,D);return z==null?I:typeof z!=typeof I||z!==I?z:this.options.trimValues?me(I,this.options.parseTagValue,this.options.numberParseOptions):I.trim()===I?me(I,this.options.parseTagValue,this.options.numberParseOptions):I}}i($,"parseTextData"),r($,"parseTextData");function V(I){if(this.options.removeNSPrefix){let v=I.split(":"),_=I.charAt(0)==="/"?"/":"";if(v[0]==="xmlns")return"";v.length===2&&(I=_+v[1])}return I}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function T(I,v,_){if(!this.options.ignoreAttributes&&typeof I=="string"){let B=L.getAllMatches(I,j),N=B.length,D={};for(let ne=0;ne<N;ne++){let z=this.resolveNameSpace(B[ne][1]),U=B[ne][4],de=this.options.attributeNamePrefix+z;if(z.length)if(this.options.transformAttributeName&&(de=this.options.transformAttributeName(de)),de==="__proto__"&&(de="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let se=this.options.attributeValueProcessor(z,U,v);se==null?D[de]=U:typeof se!=typeof U||se!==U?D[de]=se:D[de]=me(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[de]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=D,ne}return D}}i(T,"buildAttributesMap"),r(T,"buildAttributesMap");var E=r(function(I){I=I.replace(/\r\n?/g,`
91
91
  `);let v=new S("!xml"),_=v,B="",N="";for(let D=0;D<I.length;D++)if(I[D]==="<")if(I[D+1]==="/"){let z=w(I,">",D,"Closing Tag is not closed."),U=I.substring(D+2,z).trim();if(this.options.removeNSPrefix){let ke=U.indexOf(":");ke!==-1&&(U=U.substr(ke+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&(B=this.saveTextToParentTag(B,_,N));let de=N.substring(N.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let se=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(se=N.lastIndexOf(".",N.lastIndexOf(".")-1),this.tagsNodeStack.pop()):se=N.lastIndexOf("."),N=N.substring(0,se),_=this.tagsNodeStack.pop(),B="",D=z}else if(I[D+1]==="?"){let z=O(I,D,!1,"?>");if(!z)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,_,N),!(this.options.ignoreDeclaration&&z.tagName==="?xml"||this.options.ignorePiTags)){let U=new S(z.tagName);U.add(this.options.textNodeName,""),z.tagName!==z.tagExp&&z.attrExpPresent&&(U[":@"]=this.buildAttributesMap(z.tagExp,N,z.tagName)),this.addChild(_,U,N)}D=z.closeIndex+1}else if(I.substr(D+1,3)==="!--"){let z=w(I,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=I.substring(D+4,z-2);B=this.saveTextToParentTag(B,_,N),_.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=z}else if(I.substr(D+1,2)==="!D"){let z=H(I,D);this.docTypeEntities=z.entities,D=z.i}else if(I.substr(D+1,2)==="!["){let z=w(I,"]]>",D,"CDATA is not closed.")-2,U=I.substring(D+9,z);B=this.saveTextToParentTag(B,_,N);let de=this.parseTextData(U,_.tagname,N,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):_.add(this.options.textNodeName,de),D=z+2}else{let z=O(I,D,this.options.removeNSPrefix),U=z.tagName,de=z.rawTagName,se=z.tagExp,ke=z.attrExpPresent,rs=z.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&B&&_.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,_,N,!1));let os=_;if(os&&this.options.unpairedTags.indexOf(os.tagname)!==-1&&(_=this.tagsNodeStack.pop(),N=N.substring(0,N.lastIndexOf("."))),U!==v.tagname&&(N+=N?"."+U:U),this.isItStopNode(this.options.stopNodes,N,U)){let Ae="";if(se.length>0&&se.lastIndexOf("/")===se.length-1)D=z.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=z.closeIndex;else{let lr=this.readStopNodeData(I,de,rs+1);if(!lr)throw new Error(`Unexpected end of ${de}`);D=lr.i,Ae=lr.tagContent}let cr=new S(U);U!==se&&ke&&(cr[":@"]=this.buildAttributesMap(se,N,U)),Ae&&(Ae=this.parseTextData(Ae,U,N,!0,ke,!0,!0)),N=N.substr(0,N.lastIndexOf(".")),cr.add(this.options.textNodeName,Ae),this.addChild(_,cr,N)}else{if(se.length>0&&se.lastIndexOf("/")===se.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),N=N.substr(0,N.length-1),se=U):se=se.substr(0,se.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Ae=new S(U);U!==se&&ke&&(Ae[":@"]=this.buildAttributesMap(se,N,U)),this.addChild(_,Ae,N),N=N.substr(0,N.lastIndexOf("."))}else{let Ae=new S(U);this.tagsNodeStack.push(_),U!==se&&ke&&(Ae[":@"]=this.buildAttributesMap(se,N,U)),this.addChild(_,Ae,N),_=Ae}B="",D=rs}}else B+=I[D];return v.child},"parseXml");function M(I,v,_){let B=this.options.updateTag(v.tagname,_,v[":@"]);B===!1||(typeof B=="string"&&(v.tagname=B),I.addChild(v))}i(M,"addChild"),r(M,"addChild");var ce=r(function(I){if(this.options.processEntities){for(let v in this.docTypeEntities){let _=this.docTypeEntities[v];I=I.replace(_.regx,_.val)}for(let v in this.lastEntities){let _=this.lastEntities[v];I=I.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let v in this.htmlEntities){let _=this.htmlEntities[v];I=I.replace(_.regex,_.val)}I=I.replace(this.ampEntity.regex,this.ampEntity.val)}return I},"replaceEntitiesValue");function X(I,v,_,B){return I&&(B===void 0&&(B=Object.keys(v.child).length===0),I=this.parseTextData(I,v.tagname,_,!1,v[":@"]?Object.keys(v[":@"]).length!==0:!1,B),I!==void 0&&I!==""&&v.add(this.options.textNodeName,I),I=""),I}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(I,v,_){let B="*."+_;for(let N in I){let D=I[N];if(B===D||v===D)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Se(I,v,_=">"){let B,N="";for(let D=v;D<I.length;D++){let ne=I[D];if(B)ne===B&&(B="");else if(ne==='"'||ne==="'")B=ne;else if(ne===_[0])if(_[1]){if(I[D+1]===_[1])return{data:N,index:D}}else return{data:N,index:D};else ne===" "&&(ne=" ");N+=ne}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function w(I,v,_,B){let N=I.indexOf(v,_);if(N===-1)throw new Error(B);return N+v.length-1}i(w,"findClosingIndex"),r(w,"findClosingIndex");function O(I,v,_,B=">"){let N=Se(I,v+1,B);if(!N)return;let D=N.data,ne=N.index,z=D.search(/\s/),U=D,de=!0;z!==-1&&(U=D.substring(0,z),D=D.substring(z+1).trimStart());let se=U;if(_){let ke=U.indexOf(":");ke!==-1&&(U=U.substr(ke+1),de=U!==N.data.substr(ke+1))}return{tagName:U,tagExp:D,closeIndex:ne,attrExpPresent:de,rawTagName:se}}i(O,"readTagExp"),r(O,"readTagExp");function G(I,v,_){let B=_,N=1;for(;_<I.length;_++)if(I[_]==="<")if(I[_+1]==="/"){let D=w(I,">",_,`${v} is not closed`);if(I.substring(_+2,D).trim()===v&&(N--,N===0))return{tagContent:I.substring(B,_),i:D};_=D}else if(I[_+1]==="?")_=w(I,"?>",_+1,"StopNode is not closed.");else if(I.substr(_+1,3)==="!--")_=w(I,"-->",_+3,"StopNode is not closed.");else if(I.substr(_+1,2)==="![")_=w(I,"]]>",_,"StopNode is not closed.")-2;else{let D=O(I,_,">");D&&((D&&D.tagName)===v&&D.tagExp[D.tagExp.length-1]!=="/"&&N++,_=D.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function me(I,v,_){if(v&&typeof I=="string"){let B=I.trim();return B==="true"?!0:B==="false"?!1:F(I,_)}else return L.isExist(I)?I:""}i(me,"parseValue"),r(me,"parseValue"),C.exports=q}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function C(q,A){return L(q,A)}i(C,"prettify"),r(C,"prettify");function L(q,A,$){let V,j={};for(let T=0;T<q.length;T++){let E=q[T],M=S(E),ce="";if($===void 0?ce=M:ce=$+"."+M,M===A.textNodeName)V===void 0?V=E[M]:V+=""+E[M];else{if(M===void 0)continue;if(E[M]){let X=L(E[M],A,ce),te=F(X,A);E[":@"]?H(X,E[":@"],ce,A):Object.keys(X).length===1&&X[A.textNodeName]!==void 0&&!A.alwaysCreateTextNode?X=X[A.textNodeName]:Object.keys(X).length===0&&(A.alwaysCreateTextNode?X[A.textNodeName]="":X=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(X)):A.isArray(M,ce,te)?j[M]=[X]:j[M]=X}}}return typeof V=="string"?V.length>0&&(j[A.textNodeName]=V):V!==void 0&&(j[A.textNodeName]=V),j}i(L,"compress"),r(L,"compress");function S(q){let A=Object.keys(q);for(let $=0;$<A.length;$++){let V=A[$];if(V!==":@")return V}}i(S,"propName"),r(S,"propName");function H(q,A,$,V){if(A){let j=Object.keys(A),T=j.length;for(let E=0;E<T;E++){let M=j[E];V.isArray(M,$+"."+M,!0,!0)?q[M]=[A[M]]:q[M]=A[M]}}}i(H,"assignAttributes"),r(H,"assignAttributes");function F(q,A){let{textNodeName:$}=A,V=Object.keys(q).length;return!!(V===0||V===1&&(q[$]||typeof q[$]=="boolean"||q[$]===0))}i(F,"isLeafTag"),r(F,"isLeafTag"),b.prettify=C}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var C=a(),L={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(w,O){O=Object.assign({},L,O);let G=[],me=!1,I=!1;w[0]==="\uFEFF"&&(w=w.substr(1));for(let v=0;v<w.length;v++)if(w[v]==="<"&&w[v+1]==="?"){if(v+=2,v=H(w,v),v.err)return v}else if(w[v]==="<"){let _=v;if(v++,w[v]==="!"){v=F(w,v);continue}else{let B=!1;w[v]==="/"&&(B=!0,v++);let N="";for(;v<w.length&&w[v]!==">"&&w[v]!==" "&&w[v]!==" "&&w[v]!==`
92
92
  `&&w[v]!=="\r";v++)N+=w[v];if(N=N.trim(),N[N.length-1]==="/"&&(N=N.substring(0,N.length-1),v--),!X(N)){let z;return N.trim().length===0?z="Invalid space after '<'.":z="Tag '"+N+"' is an invalid name.",M("InvalidTag",z,te(w,v))}let D=$(w,v);if(D===!1)return M("InvalidAttr","Attributes for '"+N+"' have open quote.",te(w,v));let ne=D.value;if(v=D.index,ne[ne.length-1]==="/"){let z=v-ne.length;ne=ne.substring(0,ne.length-1);let U=j(ne,O);if(U===!0)me=!0;else return M(U.err.code,U.err.msg,te(w,z+U.err.line))}else if(B)if(D.tagClosed){if(ne.trim().length>0)return M("InvalidTag","Closing tag '"+N+"' can't have attributes or invalid starting.",te(w,_));{let z=G.pop();if(N!==z.tagName){let U=te(w,z.tagStartPos);return M("InvalidTag","Expected closing tag '"+z.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+N+"'.",te(w,_))}G.length==0&&(I=!0)}}else return M("InvalidTag","Closing tag '"+N+"' doesn't have proper closing.",te(w,v));else{let z=j(ne,O);if(z!==!0)return M(z.err.code,z.err.msg,te(w,v-ne.length+z.err.line));if(I===!0)return M("InvalidXml","Multiple possible root nodes found.",te(w,v));O.unpairedTags.indexOf(N)!==-1||G.push({tagName:N,tagStartPos:_}),me=!0}for(v++;v<w.length;v++)if(w[v]==="<")if(w[v+1]==="!"){v++,v=F(w,v);continue}else if(w[v+1]==="?"){if(v=H(w,++v),v.err)return v}else break;else if(w[v]==="&"){let z=E(w,v);if(z==-1)return M("InvalidChar","char '&' is not expected.",te(w,v));v=z}else if(I===!0&&!S(w[v]))return M("InvalidXml","Extra text at the end",te(w,v));w[v]==="<"&&v--}}else{if(S(w[v]))continue;return M("InvalidChar","char '"+w[v]+"' is not expected.",te(w,v))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",te(w,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(v=>v.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(w){return w===" "||w===" "||w===`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.47.10",
4
+ "version": "6.47.11",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {