@zuplo/runtime 6.22.7 → 6.22.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/index.js +13 -13
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -22,17 +22,17 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as f,b as Me,e as Re,f as iu,g as
|
|
26
|
-
`).map(u=>u.trim()).join(" ");case"%O":return n(t[o++]);case"%j":try{return JSON.stringify(t[o++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(o))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Ci,"format");function $e(n,e,t,o){let r={seen:[],stylize:hu,showHidden:e??!1,depth:t??2,colors:o??!1,customInspect:!0};return r.colors&&(r.stylize=bu),tn(r,n,r.depth)}i($e,"inspect");$e.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};$e.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function hu(n,e){return n}i(hu,"stylizeNoColor");function yu(n){return typeof n=="boolean"}i(yu,"isBoolean");function Si(n){return n===void 0}i(Si,"isUndefined");function bu(n,e){let t=$e.styles[e];return t?"\x1B["+$e.colors[t][0]+"m"+n+"\x1B["+$e.colors[t][1]+"m":n}i(bu,"stylizeWithColor");function
|
|
25
|
+
import{a as f,b as Me,e as Re,f as iu,g as zn,h as Bn,i as su,j as au}from"./chunk-AVPEK25G.js";import{a as i,b as ou,c as ru}from"./chunk-PPV7V43C.js";var Ss=ou(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.parse=Ju;yn.serialize=Ku;var ju=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zu=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Bu=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Gu=/^[\u0020-\u003A\u003D-\u007E]*$/,Vu=Object.prototype.toString,Wu=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function Ju(n,e){let t=new Wu,o=n.length;if(o<2)return t;let r=e?.decode||Qu,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?o:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=Cs(n,s,a),d=Os(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let h=Cs(n,a+1,c),y=Os(n,c,h),C=r(n.slice(h,y));t[p]=C}s=c+1}while(s<o);return t}i(Ju,"parse");function Cs(n,e,t){do{let o=n.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<t);return t}i(Cs,"startIndex");function Os(n,e,t){for(;e>t;){let o=n.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return t}i(Os,"endIndex");function Ku(n,e,t){let o=t?.encode||encodeURIComponent;if(!ju.test(n))throw new TypeError(`argument name is invalid: ${n}`);let r=o(e);if(!zu.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+r;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge}if(t.domain){if(!Bu.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!Gu.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!Yu(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():t.sameSite){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}i(Ku,"serialize");function Qu(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(Qu,"decode");function Yu(n){return Vu.call(n)==="[object Date]"}i(Yu,"isDate")});var uu=!1;function ut(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(ut,"code");function ct(n,e){return uu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(ct,"run");function cu(n){return ct(n,ut([31],39))}i(cu,"red");function lu(n){return ct(n,ut([32],39))}i(lu,"green");function du(n){return ct(n,ut([33],39))}i(du,"yellow");function pu(n){return ct(n,ut([34],39))}i(pu,"blue");function mu(n){return ct(n,ut([35],39))}i(mu,"magenta");function gu(n){return ct(n,ut([36],39))}i(gu,"cyan");var Kd=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var Ti=[cu,lu,du,pu,mu,gu];function fu(n){let e=0,t=n.length,o=0;if(t>0)for(;o<t;)e=(e<<5)-e+n.charCodeAt(o++)|0;return e}i(fu,"hashCode");function vi(n){let e=Math.abs(fu(n));return Ti[e%Ti.length]}i(vi,"generateColor");function Ci(n,e,...t){let o=0,r=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(o>=r)return a;switch(a){case"%s":return String(t[o++]);case"%d":return Number(t[o++]).toString();case"%o":return n(t[o++]).split(`
|
|
26
|
+
`).map(u=>u.trim()).join(" ");case"%O":return n(t[o++]);case"%j":try{return JSON.stringify(t[o++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(o))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Ci,"format");function $e(n,e,t,o){let r={seen:[],stylize:hu,showHidden:e??!1,depth:t??2,colors:o??!1,customInspect:!0};return r.colors&&(r.stylize=bu),tn(r,n,r.depth)}i($e,"inspect");$e.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};$e.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function hu(n,e){return n}i(hu,"stylizeNoColor");function yu(n){return typeof n=="boolean"}i(yu,"isBoolean");function Si(n){return n===void 0}i(Si,"isUndefined");function bu(n,e){let t=$e.styles[e];return t?"\x1B["+$e.colors[t][0]+"m"+n+"\x1B["+$e.colors[t][1]+"m":n}i(bu,"stylizeWithColor");function Gn(n){return typeof n=="function"}i(Gn,"isFunction");function Ai(n){return typeof n=="string"}i(Ai,"isString");function wu(n){return typeof n=="number"}i(wu,"isNumber");function ki(n){return n===null}i(ki,"isNull");function Li(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Li,"hasOwn");function Vn(n){return Qn(n)&&Yn(n)==="[object RegExp]"}i(Vn,"isRegExp");function Qn(n){return typeof n=="object"&&n!==null}i(Qn,"isObject");function Wn(n){return Qn(n)&&(Yn(n)==="[object Error]"||n instanceof Error)}i(Wn,"isError");function Oi(n){return Qn(n)&&Yn(n)==="[object Date]"}i(Oi,"isDate");function Yn(n){return Object.prototype.toString.call(n)}i(Yn,"objectToString");function Ru(n){let e={};return n.forEach(function(t,o){e[t]=!0}),e}i(Ru,"arrayToHash");function Pu(n,e,t,o,r){let s=[];for(let a=0,u=e.length;a<u;++a)Li(e,String(a))?s.push(Kn(n,e,t,o,String(a),!0)):s.push("");return r.forEach(function(a){a.match(/^\d+$/)||s.push(Kn(n,e,t,o,a,!0))}),s}i(Pu,"formatArray");function Jn(n){return"["+Error.prototype.toString.call(n)+"]"}i(Jn,"formatError");function tn(n,e,t){if(n.customInspect&&e&&Gn(e.inspect)&&e.inspect!==$e&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ai(d)||(d=tn(n,d,t)),d}let o=Iu(n,e);if(o)return o;let r=Object.keys(e),s=Ru(r);try{n.showHidden&&Object.getOwnPropertyNames&&(r=Object.getOwnPropertyNames(e))}catch{}if(Wn(e)&&(r.indexOf("message")>=0||r.indexOf("description")>=0))return Jn(e);if(r.length===0){if(Gn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Vn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Oi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Wn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Gn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Vn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Oi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Wn(e)&&(a=" "+Jn(e)),r.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Vn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Pu(n,e,t,s,r):l=r.map(function(d){return Kn(n,e,t,s,d,u)}),n.seen.pop(),Eu(l,a,c)}i(tn,"formatValue");function Kn(n,e,t,o,r,s){let a,u,c;c={value:void 0};try{c.value=e[r]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,r)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Li(o,r)||(a="["+r+"]"),u||(n.seen.indexOf(c.value)<0?(ki(t)?u=tn(n,c.value,null):u=tn(n,c.value,t-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(s?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
29
29
|
`).substr(2):u=`
|
|
30
30
|
`+u.split(`
|
|
31
31
|
`).map(function(l){return" "+l}).join(`
|
|
32
|
-
`))):u=n.stylize("[Circular]","special")),Si(a)){if(s&&r.match(/^\d+$/))return u;a=JSON.stringify(""+r),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(
|
|
32
|
+
`))):u=n.stylize("[Circular]","special")),Si(a)){if(s&&r.match(/^\d+$/))return u;a=JSON.stringify(""+r),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Kn,"formatProperty");function Iu(n,e){if(Si(e))return n.stylize("undefined","undefined");if(Ai(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(wu(e))return n.stylize(""+e,"number");if(yu(e))return n.stylize(""+e,"boolean");if(ki(e))return n.stylize("null","null")}i(Iu,"formatPrimitive");function Eu(n,e,t){let o=0;return n.reduce(function(s,a){return o++,a.indexOf(`
|
|
33
33
|
`)>=0&&o++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+n.join(`,
|
|
35
|
-
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Eu,"reduceToSingleString");var _i=i((n,...e)=>Ci($e,n,e),"format");var Yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=vi(t),this.last=0,this.enabled=e.enabled.some(o=>o.test(t))}log(...e){if(!this.enabled)return;let t,o=e[0];typeof o=="function"?t=o():t=String(o);let r=Date.now()-(this.last||Date.now());t=_i(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${r}ms`)}`;console.log(s),this.last=Date.now()}},Xn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function xu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(xu,"extract");var nn;function ye(n){let e=globalThis.DEBUG;nn||(nn=new Xn(xu(e)));let t=new Yn(nn,n);return nn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(ye,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var Xe=ye("zuplo:runtime:external-service");function Tu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=f.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Tu,"getServiceAuth");async function Ni(n,e){let t=Tu();if(t)if(Xe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let o=new URL(n),r=o.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[r])u=`https://${t.customServiceMapping[r]}`;else if(f.instance.useLegacyServiceRouting)u=`https://${r}.zuptunnel.com`;else{Xe("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await vu(r,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),h=Di(d.ENVIRONMENT_TYPE),y=await eo(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${h}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw Xe("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${o.pathname}${o.search}`);Xe(`Calling external service: ${c.toString()}`);let l=await H.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new k("Could not connect to secure tunnel.");return l}else throw Xe("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw Xe("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(Ni,"externalServiceHandler");async function vu(n,e,t,o){let r=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Di(o);Xe(`Hashing service name: ${s}-${r}.${s}-${a}-${u}`);let c=await eo(`${s}-${r}`),l=await eo(`${s}-${a}-${u}`);return`${c}.${l}`}i(vu,"hashServiceName");async function eo(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("").slice(0,-1)}i(eo,"hashSegment");function Di(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Di,"sanitizeEnvironmentType");var Ui=new Map;Ui.set("service:",Ni);var Mi=globalThis.fetch;function to(n,e){let t=Cu(e);if(typeof n=="string"){let o=new URL(n),r=Ui.get(o.protocol);return r?r(n,t):Mi(n,t)}else return Mi(n,t)}i(to,"internalFetch");globalThis.fetch=to;var Cu=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Ou={fetch:to},H=Ou;Function.prototype.toString=function(){return"[native code]"};var on=globalThis,qi=on.caches;if(qi){let n=qi.open;on.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete on.caches.default,Object.freeze(on.caches)}var Zi=new Map,no=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,s)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=Zi.get(e);o||(o=new no(t),Zi.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var oo="__zuplo-expiry-header",Lt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let s=r.headers.get(oo);if(!s){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(oo,`${Date.now()+o*1e3}`);let s=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(oo,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),s=new Response("",{headers:t});await o.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ie=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(o),this.#n=new Lt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},s=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(s)}};var Hi="zuplo-request-id",lt="zp-rid",ro="zp-body-removed",et="cf-ray",$i="x-real-ip",io="cf-ipcity",so="cf-ipcontinent",ao="cf-ipcountry",uo="cf-iplongitude",co="cf-iplatitude",Fi="cf-region",ji="cf-region-code",zi="cf-metro-code",Bi="cf-postal-code",Gi="cf-timezone",Vi="zp-ipcity",Wi="zp-ipcontinent",Ji="zp-ipcountry",Ki="zp-iplongitude",Qi="zp-iplatitude",Yi="true-client-ip",lo="zp-asn",po="zp-asorg",mo="zp-colo",go="zp-postalcode",fo="zp-metrocode",ho="zp-region",yo="zp-regioncode",bo="zp-timezone",Xi=[io,so,ao,uo,co,lo,po,mo,go,fo,ho,yo,bo],es=["zp-","cf-"],ts=[lt,et,ro];var _t=Symbol("zuplo_meters"),Nt=Symbol("zuplo_dynamic_meters"),rn="system-logger";var re=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as wc}from"@opentelemetry/api";import{SpanStatusCode as Su,trace as Au}from"@opentelemetry/api";import{SpanStatusCode as Io,trace as Eo}from"@opentelemetry/api";var ns=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function os(n){ns=n}i(os,"setTelemetryInitFunction");var rs=i(n=>ns(n),"proxyHandler");var je=class{static{i(this,"RuntimePlugin")}},Se=class extends je{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},sn=class extends Se{static{i(this,"MeteringPlugin")}},Dt=class extends je{static{i(this,"TelemetryPlugin")}};var an=new Set,is=new Set;function g(n){is.has(n)||(is.add(n),an.add(n))}i(g,"trackFeature");function ss(){let n=[...an];return an.clear(),n}i(ss,"getUnsentFeatures");function as(n){for(let e of n)an.add(e)}i(as,"restoreFeatures");var Mt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},tt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await Mt.problemResponseFormat(e,t,o)}};function un(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&un(t)}return Object.freeze(n)}i(un,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return un(this.#e)}get params(){return un(this.#t)}user};var xo={},Ue=[],wo=[],Ro=[],Po=[];var cn={addPlugin(n){Ue.push(n)},addRequestHook(n){wo.push(n)},addResponseSendingHook(n){Ro.push(n)},addResponseSendingFinalHook(n){Po.push(n)}},cs=i(async(n,e)=>{if(wo.length===0)return n;let t=Eo.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of wo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:Io.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),ls=i(async(n,e,t)=>{if(Ro.length===0)return n;let o=Eo.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of Ro)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Io.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),ds=i(async(n,e,t)=>{if(Po.length===0)return;let o=Eo.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of Po)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Io.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),us=!1;async function ps(n){if(!us){n&&(g("runtime.extensions"),await n(cn)),xo.value=cn;for(let e of Ue)if(e instanceof Dt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});os(t)}await Promise.all(Ue.map(async e=>{e instanceof Se&&await e.initialize(cn)})),Mt.setProblemResponseFormat(cn.problemResponseFormat),us=!0}}i(ps,"initializeRuntime");var To={Json:"application/json",Form:"application/x-www-form-urlencoded"};function vo(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(To.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(To.Json)||!e?JSON.stringify(n):n}i(vo,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>Au.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){let c=t.errorHandler(o,r,"Error executing request handler.",u);return a.setStatus({code:Su.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async P=>{let S=a.pop();return S?S(r,s,t,u):await this.#e(async F=>{let z=await o(F,s);return ku(z)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(dt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ut(r,l);s.dispatchEvent(p);let h=Ie.getContextExtensions(s),y=h.latestRequest,C;try{C=await p.mutableResponse}catch(P){return t.errorHandler(r,s,"Error retrieving mutableResponse",P)}try{C=await h.onResponseSending(C,y,s)}catch(P){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",P)}try{C=await ls(C,y,s)}catch(P){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",P)}s.dispatchEvent(new qt(r,C));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",P),P}try{await ds(l,y,s)}catch(P){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",P),P}return C},"#toZuploPipeline")};function ku(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(vo(n),{headers:{"content-type":"application/json"}})}i(ku,"resultToResponse");var ze=class extends je{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new K(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var ln=class{static{i(this,"EllieMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:o}=f.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=ss(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=await H.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),as(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send metrics to Ellie.",t)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=s,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var he=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(et)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=Ie.getContextExtensions(e).latestRequest,h={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new ln(e)),Ue.forEach(C=>{if(C instanceof ze){let P=C.getTransport();y.push(P)}}),y.forEach(C=>{C.pushMetrics(h,e)}),a},"metricsProcessor");var Co=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=f.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new pe({processors:[he],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var dn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(dn||{}),ms={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Lu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Oo=Lu;function _u(n){return`${new URL(n.url).pathname}`}i(_u,"instance");function Nu(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},o=n.headers.get(et);return o&&(t.rayId=o),t}i(Nu,"trace");var Du=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:_u(e),trace:Nu(e,t),...o},additionalHeaders:r,statusText:Oo[n.status]}),"merge"),So=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?tt.format(e,t,o):tt.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ms[e],...t}}},E=class extends So{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=Du(this.getProblemFromStatus(e),t,o,r,s);return tt.format(a,t,o)}static continue=i((e,t,o,r)=>this.#e(200,e,t,o,r),"continue");static switchingProtocols=i((e,t,o,r)=>this.#e(101,e,t,o,r),"switchingProtocols");static processing=i((e,t,o,r)=>this.#e(102,e,t,o,r),"processing");static earlyHints=i((e,t,o,r)=>this.#e(103,e,t,o,r),"earlyHints");static ok=i((e,t,o,r)=>this.#e(200,e,t,o,r),"ok");static created=i((e,t,o,r)=>this.#e(201,e,t,o,r),"created");static accepted=i((e,t,o,r)=>this.#e(202,e,t,o,r),"accepted");static nonAuthoritativeInformation=i((e,t,o,r)=>this.#e(203,e,t,o,r),"nonAuthoritativeInformation");static noContent=i((e,t,o,r)=>this.#e(204,e,t,o,r),"noContent");static resetContent=i((e,t,o,r)=>this.#e(205,e,t,o,r),"resetContent");static partialContent=i((e,t,o,r)=>this.#e(206,e,t,o,r),"partialContent");static multiStatus=i((e,t,o,r)=>this.#e(207,e,t,o,r),"multiStatus");static alreadyReported=i((e,t,o,r)=>this.#e(208,e,t,o,r),"alreadyReported");static imUsed=i((e,t,o,r)=>this.#e(226,e,t,o,r),"imUsed");static multipleChoices=i((e,t,o,r)=>this.#e(300,e,t,o,r),"multipleChoices");static movedPermanently=i((e,t,o,r)=>this.#e(301,e,t,o,r),"movedPermanently");static found=i((e,t,o,r)=>this.#e(302,e,t,o,r),"found");static seeOther=i((e,t,o,r)=>this.#e(303,e,t,o,r),"seeOther");static notModified=i((e,t,o,r)=>this.#e(304,e,t,o,r),"notModified");static useProxy=i((e,t,o,r)=>this.#e(305,e,t,o,r),"useProxy");static switchProxy=i((e,t,o,r)=>this.#e(306,e,t,o,r),"switchProxy");static temporaryRedirect=i((e,t,o,r)=>this.#e(307,e,t,o,r),"temporaryRedirect");static permanentRedirect=i((e,t,o,r)=>this.#e(308,e,t,o,r),"permanentRedirect");static badRequest=i((e,t,o,r)=>this.#e(400,e,t,o,r),"badRequest");static unauthorized=i((e,t,o,r)=>this.#e(401,e,t,o,r),"unauthorized");static paymentRequired=i((e,t,o,r)=>this.#e(402,e,t,o,r),"paymentRequired");static forbidden=i((e,t,o,r)=>this.#e(403,e,t,o,r),"forbidden");static notFound=i((e,t,o,r)=>this.#e(404,e,t,o,r),"notFound");static methodNotAllowed=i((e,t,o,r)=>this.#e(405,e,t,o,r),"methodNotAllowed");static notAcceptable=i((e,t,o,r)=>this.#e(406,e,t,o,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,o,r)=>this.#e(407,e,t,o,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,o,r)=>this.#e(408,e,t,o,r),"requestTimeout");static conflict=i((e,t,o,r)=>this.#e(409,e,t,o,r),"conflict");static gone=i((e,t,o,r)=>this.#e(410,e,t,o,r),"gone");static lengthRequired=i((e,t,o,r)=>this.#e(411,e,t,o,r),"lengthRequired");static preconditionFailed=i((e,t,o,r)=>this.#e(412,e,t,o,r),"preconditionFailed");static contentTooLarge=i((e,t,o,r)=>this.#e(413,e,t,o,r),"contentTooLarge");static uriTooLong=i((e,t,o,r)=>this.#e(414,e,t,o,r),"uriTooLong");static unsupportedMediaType=i((e,t,o,r)=>this.#e(415,e,t,o,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,o,r)=>this.#e(416,e,t,o,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,o,r)=>this.#e(417,e,t,o,r),"expectationFailed");static imATeapot=i((e,t,o,r)=>this.#e(418,e,t,o,r),"imATeapot");static misdirectedRequest=i((e,t,o,r)=>this.#e(421,e,t,o,r),"misdirectedRequest");static unprocessableContent=i((e,t,o,r)=>this.#e(422,e,t,o,r),"unprocessableContent");static locked=i((e,t,o,r)=>this.#e(423,e,t,o,r),"locked");static failedDependency=i((e,t,o,r)=>this.#e(424,e,t,o,r),"failedDependency");static tooEarly=i((e,t,o,r)=>this.#e(425,e,t,o,r),"tooEarly");static upgradeRequired=i((e,t,o,r)=>this.#e(426,e,t,o,r),"upgradeRequired");static preconditionRequired=i((e,t,o,r)=>this.#e(428,e,t,o,r),"preconditionRequired");static tooManyRequests=i((e,t,o,r)=>this.#e(429,e,t,o,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,o,r)=>this.#e(431,e,t,o,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,o,r)=>this.#e(451,e,t,o,r),"unavailableForLegalReasons");static internalServerError=i((e,t,o,r)=>this.#e(500,e,t,o,r),"internalServerError");static notImplemented=i((e,t,o,r)=>this.#e(501,e,t,o,r),"notImplemented");static badGateway=i((e,t,o,r)=>this.#e(502,e,t,o,r),"badGateway");static serviceUnavailable=i((e,t,o,r)=>this.#e(503,e,t,o,r),"serviceUnavailable");static gatewayTimeout=i((e,t,o,r)=>this.#e(504,e,t,o,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,o,r)=>this.#e(505,e,t,o,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,o,r)=>this.#e(506,e,t,o,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,o,r)=>this.#e(507,e,t,o,r),"insufficientStorage");static loopDetected=i((e,t,o,r)=>this.#e(508,e,t,o,r),"loopDetected");static notExtended=i((e,t,o,r)=>this.#e(510,e,t,o,r),"notExtended");static networkAuthenticationRequired=i((e,t,o,r)=>this.#e(511,e,t,o,r),"networkAuthenticationRequired")};var{toString:Mu}=Object.prototype,{propertyIsEnumerable:Uu}=Object.prototype;function Ao(n){return Mu.call(n)}i(Ao,"toString");function Ee(n){return typeof n=="string"}i(Ee,"isString");function pt(n){return Ee(n)&&n!==""}i(pt,"isNonEmptyString");function gs(n){return Ao(n)==="[object RegExp]"}i(gs,"isRegexp");function fs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Uu.call(n,e))]}i(fs,"getOwnEnumerableKeys");function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(nt,"isObject");function ko(n){return typeof n=="number"&&!isNaN(n)}i(ko,"isNumber");function Lo(n){return n===!0||n===!1}i(Lo,"isBoolean");function hs(n){return typeof n>"u"}i(hs,"isUndefined");function ys(n){return hs(n)||n===null}i(ys,"isUndefinedOrNull");function Zt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Zt,"isErrorLike");var bs=new Map;function Be(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new m("Malformed input string");let e=bs.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return bs.set(n,o),o}i(Be,"statusCodesStringToNumberArray");function qe(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(s=>{if(r===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(qe,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ws(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!nt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!ko(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Lo(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=_o(t,"allowedHeaders"),r=_o(t,"allowedMethods"),s=_o(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ws,"parseCorsPolicies");function _o(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}i(_o,"parseOptionalProperty");var pn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),mn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var No=i((n,e)=>{let t=e.routeData.corsPolicies,o=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return E.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(c,l);if(!h)return E.notFound(a,u);let y=h.routeConfiguration,C=qu(l,d,p,y,t);return C.isValid?new Response(void 0,{status:200,statusText:"OK",headers:C.headers}):(C.error&&u.log.warn(C.error),E.notFound(a,u))},"optionsHandler"),r=new pe({processors:[he],handler:o,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),qu=i((n,e,t,o,r)=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=pn(a.allowedOrigins,t);return u?{isValid:!0,headers:mn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Rs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new pe({processors:[he],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var Ge=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var Zu=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ps=i((n,e)=>{let t=i(async(r,s)=>{let a=xo.value?.notFoundHandler;if(a){let u=new URL(r.url);return a(r,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Ge)}})}return E.notFound(r,s)},"notFoundHandler"),o=new pe({processors:[he],handler:t,gateway:e});n.addRoute(Zu,o.execute)},"registerNotMatchedHandler");var Hu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Is=i(n=>{Hu.forEach(e=>n.delete(e))},"stripCorsHeaders"),gn=i(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Is(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await o(n);if(!(s instanceof Response))throw new K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=$u(r,t.routeData.corsPolicies),u=Fu(n,a),c=new Headers(s.headers);return Is(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),$u=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Fu=i((n,e)=>{let t=pn(e.allowedOrigins,n.headers.get("origin"));return t?mn(e,t):{}},"getCorsHeaders");var Do=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new pe({processors:[gn],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Es,trace as xs}from"@opentelemetry/api";var Ze={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var fn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ue=class extends fn{static{i(this,"InboundPolicy")}},Ve=class extends fn{static{i(this,"OutboundPolicy")}};var qo=class extends ue{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Zo=class extends Ve{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},Mo=new Map;function Ht(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!Mo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ue)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new qo(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}' (typeof handler '${typeof c.handler}')`);Mo.set(a.name,c)}),t.map(s=>{let a=Mo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Ht,"getInboundPolicyInstances");var Uo=new Map;function $t(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],o=n.path),t.filter(s=>!Uo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${o}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ve)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Zo(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}'`);Uo.set(a.name,c)}),t.map(s=>{let a=Uo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i($t,"getOutboundPolicyInstances");var Ho=i(n=>async(e,t)=>{let o=Ie.getContextExtensions(t),r=xs.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Es.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),$o=i(n=>async(e,t,o)=>{let r=xs.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Ze.PolicyName,c.policyName),d.setAttribute(Ze.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Es.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),mt=i(async(n,e,t,o)=>{let r=Ht(e.route,t.routeData.policies),s=$t(e.route,t.routeData.policies);return vs({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Ts({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>vs({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ts,"createInternalPolicyProcessor");async function vs({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=Ho(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=$o(o),d;return f.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return r.errorHandler(n,e,"Error executing policies",u)}}i(vs,"executePolicyProcessor");var As=ru(Ss(),1);function ks(n,e){try{let t=/v\d+(-\d+)?/g,r=(0,As.parse)(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}i(ks,"devPortalBaseURL");var Ls="/__zuplo/dev-portal",Xu="dev-portal-id",ec="dev-portal-host",tc="zp-account",nc="zp-project",oc="dev-portal-build",rc=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Eu,"reduceToSingleString");var _i=i((n,...e)=>Ci($e,n,e),"format");var Xn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=vi(t),this.last=0,this.enabled=e.enabled.some(o=>o.test(t))}log(...e){if(!this.enabled)return;let t,o=e[0];typeof o=="function"?t=o():t=String(o);let r=Date.now()-(this.last||Date.now());t=_i(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${r}ms`)}`;console.log(s),this.last=Date.now()}},eo=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function xu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(xu,"extract");var nn;function ye(n){let e=globalThis.DEBUG;nn||(nn=new eo(xu(e)));let t=new Xn(nn,n);return nn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(ye,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var Xe=ye("zuplo:runtime:external-service");function Tu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=f.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Tu,"getServiceAuth");async function Ni(n,e){let t=Tu();if(t)if(Xe(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let o=new URL(n),r=o.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[r])u=`https://${t.customServiceMapping[r]}`;else if(f.instance.useLegacyServiceRouting)u=`https://${r}.zuptunnel.com`;else{Xe("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await vu(r,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),h=Di(d.ENVIRONMENT_TYPE),y=await to(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${h}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw Xe("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${o.pathname}${o.search}`);Xe(`Calling external service: ${c.toString()}`);let l=await H.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new k("Could not connect to secure tunnel.");return l}else throw Xe("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw Xe("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(Ni,"externalServiceHandler");async function vu(n,e,t,o){let r=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Di(o);Xe(`Hashing service name: ${s}-${r}.${s}-${a}-${u}`);let c=await to(`${s}-${r}`),l=await to(`${s}-${a}-${u}`);return`${c}.${l}`}i(vu,"hashServiceName");async function to(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("").slice(0,-1)}i(to,"hashSegment");function Di(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Di,"sanitizeEnvironmentType");var Ui=new Map;Ui.set("service:",Ni);var Mi=globalThis.fetch;function no(n,e){let t=Cu(e);if(typeof n=="string"){let o=new URL(n),r=Ui.get(o.protocol);return r?r(n,t):Mi(n,t)}else return Mi(n,t)}i(no,"internalFetch");globalThis.fetch=no;var Cu=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Ou={fetch:no},H=Ou;Function.prototype.toString=function(){return"[native code]"};var on=globalThis,qi=on.caches;if(qi){let n=qi.open;on.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete on.caches.default,Object.freeze(on.caches)}var Zi=new Map,oo=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,s)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=Zi.get(e);o||(o=new oo(t),Zi.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var ro="__zuplo-expiry-header",Lt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let s=r.headers.get(ro);if(!s){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(ro,`${Date.now()+o*1e3}`);let s=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(ro,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),s=new Response("",{headers:t});await o.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ie=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(o),this.#n=new Lt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},s=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(s)}};var Hi="zuplo-request-id",lt="zp-rid",io="zp-body-removed",et="cf-ray",$i="x-real-ip",so="cf-ipcity",ao="cf-ipcontinent",uo="cf-ipcountry",co="cf-iplongitude",lo="cf-iplatitude",Fi="cf-region",ji="cf-region-code",zi="cf-metro-code",Bi="cf-postal-code",Gi="cf-timezone",Vi="zp-ipcity",Wi="zp-ipcontinent",Ji="zp-ipcountry",Ki="zp-iplongitude",Qi="zp-iplatitude",Yi="true-client-ip",po="zp-asn",mo="zp-asorg",go="zp-colo",fo="zp-postalcode",ho="zp-metrocode",yo="zp-region",bo="zp-regioncode",wo="zp-timezone",Xi=[so,ao,uo,co,lo,po,mo,go,fo,ho,yo,bo,wo],es=["zp-","cf-"],ts=[lt,et,io];var _t=Symbol("zuplo_meters"),Nt=Symbol("zuplo_dynamic_meters"),rn="system-logger";var re=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as wc}from"@opentelemetry/api";import{SpanStatusCode as Su,trace as Au}from"@opentelemetry/api";import{SpanStatusCode as Eo,trace as xo}from"@opentelemetry/api";var ns=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function os(n){ns=n}i(os,"setTelemetryInitFunction");var rs=i(n=>ns(n),"proxyHandler");var je=class{static{i(this,"RuntimePlugin")}},Se=class extends je{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},sn=class extends Se{static{i(this,"MeteringPlugin")}},Dt=class extends je{static{i(this,"TelemetryPlugin")}};var an=new Set,is=new Set;function g(n){is.has(n)||(is.add(n),an.add(n))}i(g,"trackFeature");function ss(){let n=[...an];return an.clear(),n}i(ss,"getUnsentFeatures");function as(n){for(let e of n)an.add(e)}i(as,"restoreFeatures");var Mt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},tt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await Mt.problemResponseFormat(e,t,o)}};function un(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&un(t)}return Object.freeze(n)}i(un,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return un(this.#e)}get params(){return un(this.#t)}user};var To={},Ue=[],Ro=[],Po=[],Io=[];var cn={addPlugin(n){Ue.push(n)},addRequestHook(n){Ro.push(n)},addResponseSendingHook(n){Po.push(n)},addResponseSendingFinalHook(n){Io.push(n)}},cs=i(async(n,e)=>{if(Ro.length===0)return n;let t=xo.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of Ro){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:Eo.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),ls=i(async(n,e,t)=>{if(Po.length===0)return n;let o=xo.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of Po)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Eo.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),ds=i(async(n,e,t)=>{if(Io.length===0)return;let o=xo.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of Io)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Eo.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),us=!1;async function ps(n){if(!us){n&&(g("runtime.extensions"),await n(cn)),To.value=cn;for(let e of Ue)if(e instanceof Dt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});os(t)}await Promise.all(Ue.map(async e=>{e instanceof Se&&await e.initialize(cn)})),Mt.setProblemResponseFormat(cn.problemResponseFormat),us=!0}}i(ps,"initializeRuntime");var vo={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Co(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(vo.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(vo.Json)||!e?JSON.stringify(n):n}i(Co,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>Au.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){let c=t.errorHandler(o,r,"Error executing request handler.",u);return a.setStatus({code:Su.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async P=>{let S=a.pop();return S?S(r,s,t,u):await this.#e(async F=>{let z=await o(F,s);return ku(z)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(dt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ut(r,l);s.dispatchEvent(p);let h=Ie.getContextExtensions(s),y=h.latestRequest,C;try{C=await p.mutableResponse}catch(P){return t.errorHandler(r,s,"Error retrieving mutableResponse",P)}try{C=await h.onResponseSending(C,y,s)}catch(P){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",P)}try{C=await ls(C,y,s)}catch(P){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",P)}s.dispatchEvent(new qt(r,C));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",P),P}try{await ds(l,y,s)}catch(P){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",P),P}return C},"#toZuploPipeline")};function ku(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Co(n),{headers:{"content-type":"application/json"}})}i(ku,"resultToResponse");var ze=class extends je{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new K(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var ln=class{static{i(this,"EllieMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:o}=f.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=ss(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=await H.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),as(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send metrics to Ellie.",t)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=s,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var he=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(et)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=Ie.getContextExtensions(e).latestRequest,h={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new ln(e)),Ue.forEach(C=>{if(C instanceof ze){let P=C.getTransport();y.push(P)}}),y.forEach(C=>{C.pushMetrics(h,e)}),a},"metricsProcessor");var dn=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=f.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new pe({processors:[he],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var pn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(pn||{}),ms={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Lu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Oo=Lu;function _u(n){return`${new URL(n.url).pathname}`}i(_u,"instance");function Nu(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},o=n.headers.get(et);return o&&(t.rayId=o),t}i(Nu,"trace");var Du=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:_u(e),trace:Nu(e,t),...o},additionalHeaders:r,statusText:Oo[n.status]}),"merge"),So=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?tt.format(e,t,o):tt.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ms[e],...t}}},E=class extends So{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=Du(this.getProblemFromStatus(e),t,o,r,s);return tt.format(a,t,o)}static continue=i((e,t,o,r)=>this.#e(200,e,t,o,r),"continue");static switchingProtocols=i((e,t,o,r)=>this.#e(101,e,t,o,r),"switchingProtocols");static processing=i((e,t,o,r)=>this.#e(102,e,t,o,r),"processing");static earlyHints=i((e,t,o,r)=>this.#e(103,e,t,o,r),"earlyHints");static ok=i((e,t,o,r)=>this.#e(200,e,t,o,r),"ok");static created=i((e,t,o,r)=>this.#e(201,e,t,o,r),"created");static accepted=i((e,t,o,r)=>this.#e(202,e,t,o,r),"accepted");static nonAuthoritativeInformation=i((e,t,o,r)=>this.#e(203,e,t,o,r),"nonAuthoritativeInformation");static noContent=i((e,t,o,r)=>this.#e(204,e,t,o,r),"noContent");static resetContent=i((e,t,o,r)=>this.#e(205,e,t,o,r),"resetContent");static partialContent=i((e,t,o,r)=>this.#e(206,e,t,o,r),"partialContent");static multiStatus=i((e,t,o,r)=>this.#e(207,e,t,o,r),"multiStatus");static alreadyReported=i((e,t,o,r)=>this.#e(208,e,t,o,r),"alreadyReported");static imUsed=i((e,t,o,r)=>this.#e(226,e,t,o,r),"imUsed");static multipleChoices=i((e,t,o,r)=>this.#e(300,e,t,o,r),"multipleChoices");static movedPermanently=i((e,t,o,r)=>this.#e(301,e,t,o,r),"movedPermanently");static found=i((e,t,o,r)=>this.#e(302,e,t,o,r),"found");static seeOther=i((e,t,o,r)=>this.#e(303,e,t,o,r),"seeOther");static notModified=i((e,t,o,r)=>this.#e(304,e,t,o,r),"notModified");static useProxy=i((e,t,o,r)=>this.#e(305,e,t,o,r),"useProxy");static switchProxy=i((e,t,o,r)=>this.#e(306,e,t,o,r),"switchProxy");static temporaryRedirect=i((e,t,o,r)=>this.#e(307,e,t,o,r),"temporaryRedirect");static permanentRedirect=i((e,t,o,r)=>this.#e(308,e,t,o,r),"permanentRedirect");static badRequest=i((e,t,o,r)=>this.#e(400,e,t,o,r),"badRequest");static unauthorized=i((e,t,o,r)=>this.#e(401,e,t,o,r),"unauthorized");static paymentRequired=i((e,t,o,r)=>this.#e(402,e,t,o,r),"paymentRequired");static forbidden=i((e,t,o,r)=>this.#e(403,e,t,o,r),"forbidden");static notFound=i((e,t,o,r)=>this.#e(404,e,t,o,r),"notFound");static methodNotAllowed=i((e,t,o,r)=>this.#e(405,e,t,o,r),"methodNotAllowed");static notAcceptable=i((e,t,o,r)=>this.#e(406,e,t,o,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,o,r)=>this.#e(407,e,t,o,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,o,r)=>this.#e(408,e,t,o,r),"requestTimeout");static conflict=i((e,t,o,r)=>this.#e(409,e,t,o,r),"conflict");static gone=i((e,t,o,r)=>this.#e(410,e,t,o,r),"gone");static lengthRequired=i((e,t,o,r)=>this.#e(411,e,t,o,r),"lengthRequired");static preconditionFailed=i((e,t,o,r)=>this.#e(412,e,t,o,r),"preconditionFailed");static contentTooLarge=i((e,t,o,r)=>this.#e(413,e,t,o,r),"contentTooLarge");static uriTooLong=i((e,t,o,r)=>this.#e(414,e,t,o,r),"uriTooLong");static unsupportedMediaType=i((e,t,o,r)=>this.#e(415,e,t,o,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,o,r)=>this.#e(416,e,t,o,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,o,r)=>this.#e(417,e,t,o,r),"expectationFailed");static imATeapot=i((e,t,o,r)=>this.#e(418,e,t,o,r),"imATeapot");static misdirectedRequest=i((e,t,o,r)=>this.#e(421,e,t,o,r),"misdirectedRequest");static unprocessableContent=i((e,t,o,r)=>this.#e(422,e,t,o,r),"unprocessableContent");static locked=i((e,t,o,r)=>this.#e(423,e,t,o,r),"locked");static failedDependency=i((e,t,o,r)=>this.#e(424,e,t,o,r),"failedDependency");static tooEarly=i((e,t,o,r)=>this.#e(425,e,t,o,r),"tooEarly");static upgradeRequired=i((e,t,o,r)=>this.#e(426,e,t,o,r),"upgradeRequired");static preconditionRequired=i((e,t,o,r)=>this.#e(428,e,t,o,r),"preconditionRequired");static tooManyRequests=i((e,t,o,r)=>this.#e(429,e,t,o,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,o,r)=>this.#e(431,e,t,o,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,o,r)=>this.#e(451,e,t,o,r),"unavailableForLegalReasons");static internalServerError=i((e,t,o,r)=>this.#e(500,e,t,o,r),"internalServerError");static notImplemented=i((e,t,o,r)=>this.#e(501,e,t,o,r),"notImplemented");static badGateway=i((e,t,o,r)=>this.#e(502,e,t,o,r),"badGateway");static serviceUnavailable=i((e,t,o,r)=>this.#e(503,e,t,o,r),"serviceUnavailable");static gatewayTimeout=i((e,t,o,r)=>this.#e(504,e,t,o,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,o,r)=>this.#e(505,e,t,o,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,o,r)=>this.#e(506,e,t,o,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,o,r)=>this.#e(507,e,t,o,r),"insufficientStorage");static loopDetected=i((e,t,o,r)=>this.#e(508,e,t,o,r),"loopDetected");static notExtended=i((e,t,o,r)=>this.#e(510,e,t,o,r),"notExtended");static networkAuthenticationRequired=i((e,t,o,r)=>this.#e(511,e,t,o,r),"networkAuthenticationRequired")};var{toString:Mu}=Object.prototype,{propertyIsEnumerable:Uu}=Object.prototype;function Ao(n){return Mu.call(n)}i(Ao,"toString");function Ee(n){return typeof n=="string"}i(Ee,"isString");function pt(n){return Ee(n)&&n!==""}i(pt,"isNonEmptyString");function gs(n){return Ao(n)==="[object RegExp]"}i(gs,"isRegexp");function fs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Uu.call(n,e))]}i(fs,"getOwnEnumerableKeys");function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(nt,"isObject");function ko(n){return typeof n=="number"&&!isNaN(n)}i(ko,"isNumber");function Lo(n){return n===!0||n===!1}i(Lo,"isBoolean");function hs(n){return typeof n>"u"}i(hs,"isUndefined");function ys(n){return hs(n)||n===null}i(ys,"isUndefinedOrNull");function Zt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Zt,"isErrorLike");var bs=new Map;function Be(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new m("Malformed input string");let e=bs.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return bs.set(n,o),o}i(Be,"statusCodesStringToNumberArray");function qe(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(s=>{if(r===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(qe,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ws(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!nt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!ko(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Lo(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=_o(t,"allowedHeaders"),r=_o(t,"allowedMethods"),s=_o(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ws,"parseCorsPolicies");function _o(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}i(_o,"parseOptionalProperty");var mn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),gn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var No=i((n,e)=>{let t=e.routeData.corsPolicies,o=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return E.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(c,l);if(!h)return E.notFound(a,u);let y=h.routeConfiguration,C=qu(l,d,p,y,t);return C.isValid?new Response(void 0,{status:200,statusText:"OK",headers:C.headers}):(C.error&&u.log.warn(C.error),E.notFound(a,u))},"optionsHandler"),r=new pe({processors:[he],handler:o,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),qu=i((n,e,t,o,r)=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=mn(a.allowedOrigins,t);return u?{isValid:!0,headers:gn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Rs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new pe({processors:[he],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var Ge=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var Zu=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ps=i((n,e)=>{let t=i(async(r,s)=>{let a=To.value?.notFoundHandler;if(a){let u=new URL(r.url);return a(r,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Ge)}})}return E.notFound(r,s)},"notFoundHandler"),o=new pe({processors:[he],handler:t,gateway:e});n.addRoute(Zu,o.execute)},"registerNotMatchedHandler");var Hu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Is=i(n=>{Hu.forEach(e=>n.delete(e))},"stripCorsHeaders"),fn=i(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Is(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await o(n);if(!(s instanceof Response))throw new K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=$u(r,t.routeData.corsPolicies),u=Fu(n,a),c=new Headers(s.headers);return Is(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),$u=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Fu=i((n,e)=>{let t=mn(e.allowedOrigins,n.headers.get("origin"));return t?gn(e,t):{}},"getCorsHeaders");var Do=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new pe({processors:[fn],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Es,trace as xs}from"@opentelemetry/api";var Ze={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var hn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ue=class extends hn{static{i(this,"InboundPolicy")}},Ve=class extends hn{static{i(this,"OutboundPolicy")}};var qo=class extends ue{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Zo=class extends Ve{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},Mo=new Map;function Ht(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!Mo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ue)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new qo(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}' (typeof handler '${typeof c.handler}')`);Mo.set(a.name,c)}),t.map(s=>{let a=Mo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Ht,"getInboundPolicyInstances");var Uo=new Map;function $t(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],o=n.path),t.filter(s=>!Uo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${o}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ve)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Zo(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}'`);Uo.set(a.name,c)}),t.map(s=>{let a=Uo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i($t,"getOutboundPolicyInstances");var Ho=i(n=>async(e,t)=>{let o=Ie.getContextExtensions(t),r=xs.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Es.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),$o=i(n=>async(e,t,o)=>{let r=xs.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Ze.PolicyName,c.policyName),d.setAttribute(Ze.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Es.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),mt=i(async(n,e,t,o)=>{let r=Ht(e.route,t.routeData.policies),s=$t(e.route,t.routeData.policies);return vs({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Ts({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>vs({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ts,"createInternalPolicyProcessor");async function vs({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=Ho(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=$o(o),d;return f.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return r.errorHandler(n,e,"Error executing policies",u)}}i(vs,"executePolicyProcessor");var As=ru(Ss(),1);function ks(n,e){try{let t=/v\d+(-\d+)?/g,r=(0,As.parse)(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}i(ks,"devPortalBaseURL");var Ls="/__zuplo/dev-portal",Xu="dev-portal-id",ec="dev-portal-host",tc="zp-account",nc="zp-project",oc="dev-portal-build",rc=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -78,18 +78,18 @@ import{a as f,b as Me,e as Re,f as iu,g as jn,h as zn,i as su,j as au}from"./chu
|
|
|
78
78
|
</div>
|
|
79
79
|
</body>
|
|
80
80
|
</html>
|
|
81
|
-
`},"notAvailablePage"),Ms=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,{deploymentName:o,zudokuHostUrl:r}=f.instance,s=i(async(c,l)=>{if(f.instance.isLocalDevelopment)return new Response(Ds("not-supported"),{headers:{"content-type":"text/html"}});if(!o)return E.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=d.pathname;p===t&&(p+="/");let h=new URL(`deployments/${o}${p}`,r),y=await H.fetch(h.toString(),{headers:c.headers,method:c.method,body:c.body,redirect:"manual"});return f.instance.isWorkingCopy&&y.status===404&&d.pathname===t?new Response(Ds("not-built"),{headers:{"content-type":"text/html"}}):y},"devPortalRoute"),a=new pe({processors:[he,mt],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_ZUDOKU_ROUTE",methods:["GET","HEAD"],path:`${t}(.*)`,systemRouteName:"zudoku-portal"});n.addRoute(u,a.execute)},"registerZudokuRoute");var Fo=0,Ft=class{static{i(this,"CoreLogger")}constructor(e,t,o,r,s){this.#n=t,this.#o=o??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],o=!1,r=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=o?r:s,a==e&&(o=!0)})},"#setupMethods");#t={};#n;#o;#r;#i;log(e,t,o,r,s,a){Fo>=Number.MAX_SAFE_INTEGER&&(Fo=0);let u={logId:crypto.randomUUID(),requestId:o,rayId:r,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#o,buildId:this.#r,vectorClock:Fo++};this.#t[e](u,a)}};var fe=class extends je{static{i(this,"LogPlugin")}};var
|
|
81
|
+
`},"notAvailablePage"),Ms=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,{deploymentName:o,zudokuHostUrl:r}=f.instance,s=i(async(c,l)=>{if(f.instance.isLocalDevelopment)return new Response(Ds("not-supported"),{headers:{"content-type":"text/html"}});if(!o)return E.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=d.pathname;p===t&&(p+="/");let h=new URL(`deployments/${o}${p}`,r),y=await H.fetch(h.toString(),{headers:c.headers,method:c.method,body:c.body,redirect:"manual"});return f.instance.isWorkingCopy&&y.status===404&&d.pathname===t?new Response(Ds("not-built"),{headers:{"content-type":"text/html"}}):y},"devPortalRoute"),a=new pe({processors:[he,mt],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_ZUDOKU_ROUTE",methods:["GET","HEAD"],path:`${t}(.*)`,systemRouteName:"zudoku-portal"});n.addRoute(u,a.execute)},"registerZudokuRoute");var Fo=0,Ft=class{static{i(this,"CoreLogger")}constructor(e,t,o,r,s){this.#n=t,this.#o=o??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],o=!1,r=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=o?r:s,a==e&&(o=!0)})},"#setupMethods");#t={};#n;#o;#r;#i;log(e,t,o,r,s,a){Fo>=Number.MAX_SAFE_INTEGER&&(Fo=0);let u={logId:crypto.randomUUID(),requestId:o,rayId:r,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#o,buildId:this.#r,vectorClock:Fo++};this.#t[e](u,a)}};var fe=class extends je{static{i(this,"LogPlugin")}};var bn=class{static{i(this,"LoggingContext")}constructor(e,t,o,r){this.#e=e,this.custom=t,this.originalRequest=o,this.route=r}#e;custom;originalRequest;route;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var jt=class{static{i(this,"RequestLogger")}constructor(e,t,o,r){this.#t=e,this.#n=t,this.#o=o,this.#r=r}#e="request";#t;#n;#o;#r;debug=i((...e)=>{this.#o.log("debug",this.#e,this.#t,this.#n,e,this.#r)},"debug");info=i((...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)},"info");log=i((...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)},"log");warn=i((...e)=>{this.#o.log("warn",this.#e,this.#t,this.#n,e,this.#r)},"warn");error=i((...e)=>{this.#o.log("error",this.#e,this.#t,this.#n,e,this.#r)},"error")};var ic=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),sc=new Map(ic);var ac=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],jo=Symbol(".toJSON was called"),uc=i(n=>{n[jo]=!0;let e=n.toJSON();return delete n[jo],e},"toJSON"),cc=i(n=>sc.get(n)??Error,"getErrorConstructor"),Us=i(({from:n,seen:e,to:t,forceEnumerable:o,maxDepth:r,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Zt(n)){let l=cc(n.name);t=new l}else t={};if(e.push(n),s>=r)return t;if(a&&typeof n.toJSON=="function"&&n[jo]!==!0)return uc(n);let c=i(l=>Us({from:l,seen:[...e],forceEnumerable:o,maxDepth:r,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of ac)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Zt(n[l])?c(n[l]):n[l],enumerable:o?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function rt(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,o=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Us({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:o,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(rt,"serializeError");var lc=/file:\/\/\/(.*?)\/dist\//g,dc="at async Event.respondWith";function zo(n){return typeof n!="string"?n:n.split(`
|
|
82
82
|
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let o=e.replaceAll(lc,"").replaceAll(dc,"").trim();return t===0||o.length===0?o:` ${o}`}).filter(e=>e.length>0).join(`
|
|
83
|
-
`)}i(zo,"cleanStack");function
|
|
83
|
+
`)}i(zo,"cleanStack");function wn(n,e,t=""){let o=[],r=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
84
84
|
`,newlineOrSpace:`
|
|
85
85
|
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let C=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return C.length<=u.inlineCharacterLimit?C:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
86
86
|
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(o.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||gs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>r)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";o.push(a);let y="["+p.newline+a.map((C,P)=>{let S=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(C,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+S}).join("")+p.pad+"]";return o.pop(),h(y)}if(nt(a)){let y=fs(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";o.push(a);let C="{"+p.newline+y.map((P,S)=>{let N=y.length-1===S?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",F=!A&&/^[a-z$_][$\w]*$/i.test(P),z=A||F?P:s(P,u,"",l+1),Z=s(a[P],u,c+d,l+1);return u.transform&&(Z=u.transform(a,P,Z)),p.indent+String(z)+": "+Z+N}).join("")+p.pad+"}";return o.pop(),h(C)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
87
|
-
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(
|
|
88
|
-
`)}i(qs,"messagesToMultilineText");function Zs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Zs,"stringifyNonString");function Bo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ao(n):"unknown"}i(Bo,"stringifyNonStringToText");import{importPKCS8 as pc,SignJWT as mc}from"jose";async function be(n,e,t){for(let o=0;o<=n.retries;o++){let r=H.fetch(e,t);if(o===n.retries)return r;let s=await r;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(be,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new mc(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Hs(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Go("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Hs,"exchangeIDTokenForGcpWorkloadToken");async function $s({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return js(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}i($s,"generateServiceAccountIDToken");async function Fs(n,e,t){return Go(n,{token:e,returnSecureToken:!0},t)}i(Fs,"exchangeFirebaseJwtForIdToken");async function wn(n,e,t){return Go(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(wn,"exchangeGgpJwtForIdToken");async function Go(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return js(n,o,t)}i(Go,"fetchTokenFromBody");async function js(n,e,t){let o=await be(t,n,e);if(o.status!==200){let s;try{let a=await o.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await o.json()}i(js,"fetchToken");var xe=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await pc(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var gc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},zs=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:gc[e.level],body:_e(e.messages),attributes:t}},"unifiedFormatter");async function ne(n,e){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}let t;try{t=await e?.text()}catch{}try{let o={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,vectorClock:0};await Bs(f.instance,[o])}catch(o){console.error(o)}}i(ne,"sendRemoteGlobalLog");async function Bs(n,e){let t=zs(n);try{await H.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Bs,"sendLogs");var fc=i(n=>async e=>{e.length!==0&&await Bs(n,e)},"dispatchFunction"),Rn,zt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Rn||(Rn=new Y("unified-log-transport",1,fc(e)))}async log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var Vo=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Bt(this.options)}},hc="https://logging.googleapis.com/v2/entries:write?alt=json",Wo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Bt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#o=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await xe.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:_e(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wo[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=gt(o.allMessages);s.jsonPayload={...o,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await xe.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await H.fetch(hc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});o.ok||await ne({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`]},o)}catch{await ne({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var Pn="gcp";function In(n){let e={allMessages:_e(n.messages)},t="zuplo-production",o=gt(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,severity:Wo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}i(In,"gcpLogFormat");var Gt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Pn){if(e.messages.length===0)return;this.#e[e.level](In(e))}else{let o={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:_e(e.messages)};this.#e[e.level](JSON.stringify(o))}}};var Yo=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Vt(this.options)}},Jo="__ddtags",Ko="__ddattr",Qo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),yc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(Qo(o)):t.push(`${Qo(o)}:${Qo(r.toString())}`)}),t.join(",")},"formatTags"),Vt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Jo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Jo]!==void 0);a>-1&&(Object.assign(o,s[a][Jo]),s.splice(a,1));let u={},c=t.custom[Ko];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ko]!==void 0);l>-1&&(Object.assign(u,s[l][Ko]),s.splice(l,1));let d=_e(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:gt(d),service:e.loggingId,ddtags:yc(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await ne({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await ne({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Wt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Pn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[In(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Xo=ye("zuplo:logging"),En=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),o=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;Xo("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(rn);return s?r.push(new Wt(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Gt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new zt(e)),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Ft(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){Xo("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(rn);if(a&&a.captureUserLogs===!0?o.push(new Wt(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Gt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new zt(e)),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Bt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Vt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new Ft(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s,a){Xo("Gateway.createRequestLoggers");let u=new yn(o,r,s,a),c=new jt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new jt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var ft=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},xn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var er=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,o){this.fullPath=e,this.config=t,this.executableHandler=o,this.urlPattern=new URLPattern({pathname:this.fullPath})}urlPattern;fullPath;config;executableHandler},Tn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Ge||e instanceof ce))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o;"pathPattern"in e&&e.pathPattern?o=e.pathPattern:o=e.path;try{let r=new er(o,e,t);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new xn(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}lookup(e,t){if(typeof t>"u")throw new m(`Invalid request - Method was undefined. Path: '${e}'`);for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o];if(r.config.methods.includes(t)){let s=r.urlPattern.exec({pathname:e});if(s!==null)return new ft(r.config,r.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],s=r.urlPattern.exec({pathname:e});if(s!==null){let a=new ft(r.config,r.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as bc}from"node:async_hooks";var vn={context:new bc};var tr;function Gs(n){tr=n}i(Gs,"setGlobalZuploEventContext");function ht(){if(tr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return tr}i(ht,"getGlobalZuploEventContext");function Vs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);es.includes(r.toLowerCase())&&!ts.includes(o.toLowerCase())&&t.delete(o)}t.delete($i)}else Xi.forEach(o=>{t.delete(o)});return t}i(Vs,"normalizeIncomingRequestHeaders");var We=ye("zuplo:runtime"),ge=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;We("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(We("Gateway.initialize"),!n.#e){let s=await En.init(o),a=await e(),u={...a,corsPolicies:ws(a.corsPolicies)},c=new n(u,t,s,r);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){We("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[mt,gn,he];setupRoutes=i(()=>{We("Gateway.setupRoutes");let e=this.routeData,t=new Tn;if(e.routes.length===0)return Co(t,this),Do(t,this),No(t,this),Rs(t,this),t;let{enabled:o,version:r}=this.runtimeSettings.developerPortal;o&&(r==="zudoku"?Ms(t,this):r==="legacy"&&(Ns(t,this),_s(t,this))),Co(t,this),Do(t,this),No(t,this);for(let s of Ue)s instanceof Se&&s.registerRoutes(t,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#o,handler:a,gateway:this}),c=new Ge(s);t.addRoute(c,u.execute)}),Ps(t,this),t},"setupRoutes");errorHandler(e,t,o,r){We("Gateway.internalErrorResponse"),t.log.error(o,r);let s={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy)if(r instanceof k&&r.extensionMembers)s=r.extensionMembers;else if(r.cause){let a=rt(r.cause);"stack"in a&&(a.stack=zo(a.stack)),s={cause:a}}else{let a=rt(r);"stack"in a&&(a.stack=zo(a.stack)),s={cause:a}}return E.internalServerError(e,t,{detail:r.message,...s})}async handleRequest(e,t){let o=e.headers.get(lt)??e.headers.get(Hi)??crypto.randomUUID(),r=e.headers.get(et);Gs(t);let s=Vs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(lt,o);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let A=new Headers(a.headers);A.set(ro,"true"),a=new Request(a,{headers:A,body:null})}let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:h}=this.#t.createRequestLoggers(o,r,t,d,a,l.routeConfiguration),y=new Cn(e.headers),C=new te(a,{params:l.params}),P=new On({logger:p,route:l.routeConfiguration,requestId:o,event:t,custom:d,incomingRequestProperties:y}),S=vn.context.getStore();S&&(S.context=P);let N=l.routeConfiguration.raw();wc.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[Ze.RoutePathPattern]:P.route.pathPattern,[Ze.RouteOperationId]:N.operationId,[Ze.RouteTrace]:N["x-zuplo-trace"],[Ze.RouteSystem]:dt(u)?!0:void 0}),Ie.initialize(P,C);try{if(Q.addLogger(P,h),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(u):!u.pathname.startsWith("/__zuplo")){let Z=await cs(C,P);if(Z instanceof Response)return Z;{let v=Ie.getContextExtensions(P);C=Z,v.latestRequest=C}}dt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let A=l.executableHandler;Rc(A,l,a),We("Gateway.handleRequest - call user handler");let F=await A(C,P);if(We("Gateway.handleRequest - user handler"),!(F instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof F}`);if(F.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let z;if(F.headers.get(lt)===null&&!F.webSocket){let Z=new Headers(F.headers);Z.set(lt,o),z=new Response(F.body,{status:F.status,statusText:F.statusText,headers:Z,cf:F.cf})}else z=F;return z}catch(A){return A instanceof k?(p.error(A),h.warn(A)):h.error(A),await this.errorHandler(C,P,"Error executing handler",A)}}};function Rc(n,e,t){if(We("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Rc,"checkHandler");var Ws=i(async(n,e,t)=>{let o=ge.instance.routeData.policies,r=Ht([n],o);if(r.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy"),Js=i(async(n,e,t,o)=>{let r=ge.instance.routeData.policies,s=$t([n],r);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,o)},"invokeOutboundPolicy");var Cn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(lo);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(po)??void 0}get city(){return this.#e.get(io)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(so)??this.#e.get(Wi)??void 0}get country(){return this.#e.get(ao)??this.#e.get(Ji)??void 0}get latitude(){return this.#e.get(co)??this.#e.get(Qi)??void 0}get longitude(){return this.#e.get(uo)??this.#e.get(Ki)??void 0}get colo(){return this.#e.get(mo)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(go)??void 0}get metroCode(){return this.#e.get(zi)??this.#e.get(fo)??void 0}get region(){return this.#e.get(Fi)??this.#e.get(ho)??void 0}get regionCode(){return this.#e.get(ji)??this.#e.get(yo)??void 0}get timezone(){return this.#e.get(Gi)??this.#e.get(bo)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Ut=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},qt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ie=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)},"onResponseSendingFinal");onResponseSending=i(async(e,t,o)=>{let r=e;for(let s of this.#n)r=await s(e,t,o);return r},"onResponseSending")},On=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>Ws(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Js(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ie.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ie.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}};var Pc="Error initializing gateway. Check your configuration for errors or contact support.",Ic="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",nr=class{constructor(e,t,o,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,o)=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await ps(this.runtimeInit)}catch(s){this.handleError(s,Ic,e)}return rs(i(async(s,a)=>{let u;try{u=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,Pc,s)}let c={context:void 0};return vn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,o)},"requestHandler");handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Ec(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){r+=n[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(o==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Ec,"lexer");function rr(n,e){e===void 0&&(e={});for(var t=Ec(n),o=e.prefixes,r=o===void 0?"./":o,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),h=i(function(j){var x=p(j);if(x!==void 0)return x;var I=t[l],M=I.type,le=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(le,", expected ").concat(j))},"mustConsume"),y=i(function(){for(var j="",x;x=p("CHAR")||p("ESCAPED_CHAR");)j+=x;return j},"consumeText"),C=i(function(j){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),P=i(function(j){var x=u[u.length-1],I=j||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||C(I)?"[^".concat(or(a),"]+?"):"(?:(?!".concat(or(I),")[^").concat(or(a),"])+?")},"safePattern");l<t.length;){var S=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var F=S||"";r.indexOf(F)===-1&&(d+=F,F=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:F,suffix:"",pattern:A||P(F),modifier:p("MODIFIER")||""});continue}var z=S||p("ESCAPED_CHAR");if(z){d+=z;continue}d&&(u.push(d),d="");var Z=p("OPEN");if(Z){var F=y(),v=p("NAME")||"",q=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(q?c++:""),pattern:v&&!q?P(F):q,prefix:F,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(rr,"parse");function Ks(n,e){return xc(rr(n,e),e)}i(Ks,"compile");function xc(n,e){e===void 0&&(e={});var t=Tc(e),o=e.encode,r=o===void 0?function(c){return c}:o,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",C=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!C)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var S=r(h[P],p);if(a&&!u[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var S=r(String(h),p);if(a&&!u[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!y){var N=C?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(xc,"tokensToFunction");function or(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(or,"escapeString");function Tc(n){return n&&n.sensitive?"":"i"}i(Tc,"flags");var vc=ye("zuplo:runtime"),sr=new TextEncoder,Qs={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Cc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],yt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=o,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new ar(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){vc("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=H.fetch(r,s);if(o===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},ar=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:o,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:C,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let S,N;(!c||!l)&&([S,N]=Oc(this.url,this.headers)),this.service=c||S||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(z=>C||!Cc.includes(z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(z=>z+":"+(z==="host"?this.url.host:(this.headers.get(z)||"").replace(/\s+/g," "))).join(`
|
|
87
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(wn,"stringifyObject");function He(n){return Zs(rt(n))}i(He,"serializeMessage");function _e(n){return n.map(e=>He(e))}i(_e,"serializeMessages");function gt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Zs(rt(e))}i(gt,"extractBestMessage");function qs(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Zt(t))if(t.stack)e.push(t.stack);else{let o=wn(rt(t));e.push(o)}else if(typeof t=="object"){let o=wn(t);e.push(o)}else{let o=Bo(t);e.push(o)}}),e.join(`
|
|
88
|
+
`)}i(qs,"messagesToMultilineText");function Zs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Zs,"stringifyNonString");function Bo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ao(n):"unknown"}i(Bo,"stringifyNonStringToText");import{importPKCS8 as pc,SignJWT as mc}from"jose";async function be(n,e,t){for(let o=0;o<=n.retries;o++){let r=H.fetch(e,t);if(o===n.retries)return r;let s=await r;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(be,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new mc(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Hs(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Go("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Hs,"exchangeIDTokenForGcpWorkloadToken");async function $s({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return js(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}i($s,"generateServiceAccountIDToken");async function Fs(n,e,t){return Go(n,{token:e,returnSecureToken:!0},t)}i(Fs,"exchangeFirebaseJwtForIdToken");async function Rn(n,e,t){return Go(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Rn,"exchangeGgpJwtForIdToken");async function Go(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return js(n,o,t)}i(Go,"fetchTokenFromBody");async function js(n,e,t){let o=await be(t,n,e);if(o.status!==200){let s;try{let a=await o.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await o.json()}i(js,"fetchToken");var xe=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await pc(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var gc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},zs=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:gc[e.level],body:_e(e.messages),attributes:t}},"unifiedFormatter");async function ne(n,e){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}let t;try{t=await e?.text()}catch{}try{let o={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,vectorClock:0};await Bs(f.instance,[o])}catch(o){console.error(o)}}i(ne,"sendRemoteGlobalLog");async function Bs(n,e){let t=zs(n);try{await H.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Bs,"sendLogs");var fc=i(n=>async e=>{e.length!==0&&await Bs(n,e)},"dispatchFunction"),Pn,zt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Pn||(Pn=new Y("unified-log-transport",1,fc(e)))}async log(e,t){Pn.enqueue(e),t.waitUntil(Pn.waitUntilFlushed())}};var Vo=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Bt(this.options)}},hc="https://logging.googleapis.com/v2/entries:write?alt=json",Wo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Bt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#o=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await xe.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:_e(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wo[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=gt(o.allMessages);s.jsonPayload={...o,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await xe.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await H.fetch(hc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});o.ok||await ne({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`]},o)}catch{await ne({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var In="gcp";function En(n){let e={allMessages:_e(n.messages)},t="zuplo-production",o=gt(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,severity:Wo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}i(En,"gcpLogFormat");var Gt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level](En(e))}else{let o={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:_e(e.messages)};this.#e[e.level](JSON.stringify(o))}}};var Yo=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Vt(this.options)}},Jo="__ddtags",Ko="__ddattr",Qo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),yc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(Qo(o)):t.push(`${Qo(o)}:${Qo(r.toString())}`)}),t.join(",")},"formatTags"),Vt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Jo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Jo]!==void 0);a>-1&&(Object.assign(o,s[a][Jo]),s.splice(a,1));let u={},c=t.custom[Ko];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ko]!==void 0);l>-1&&(Object.assign(u,s[l][Ko]),s.splice(l,1));let d=_e(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:gt(d),service:e.loggingId,ddtags:yc(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await ne({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await ne({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Wt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level].apply(null,[En(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Xo=ye("zuplo:logging"),xn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),o=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;Xo("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(rn);return s?r.push(new Wt(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Gt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new zt(e)),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Ft(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){Xo("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(rn);if(a&&a.captureUserLogs===!0?o.push(new Wt(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Gt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new zt(e)),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Bt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Vt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new Ft(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s,a){Xo("Gateway.createRequestLoggers");let u=new bn(o,r,s,a),c=new jt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new jt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var ft=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Tn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var er=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,o){this.fullPath=e,this.config=t,this.executableHandler=o,this.urlPattern=new URLPattern({pathname:this.fullPath})}urlPattern;fullPath;config;executableHandler},vn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Ge||e instanceof ce))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o;"pathPattern"in e&&e.pathPattern?o=e.pathPattern:o=e.path;try{let r=new er(o,e,t);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new Tn(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}lookup(e,t){if(typeof t>"u")throw new m(`Invalid request - Method was undefined. Path: '${e}'`);for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o];if(r.config.methods.includes(t)){let s=r.urlPattern.exec({pathname:e});if(s!==null)return new ft(r.config,r.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],s=r.urlPattern.exec({pathname:e});if(s!==null){let a=new ft(r.config,r.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as bc}from"node:async_hooks";var Cn={context:new bc};var tr;function Gs(n){tr=n}i(Gs,"setGlobalZuploEventContext");function ht(){if(tr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return tr}i(ht,"getGlobalZuploEventContext");function Vs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);es.includes(r.toLowerCase())&&!ts.includes(o.toLowerCase())&&t.delete(o)}t.delete($i)}else Xi.forEach(o=>{t.delete(o)});return t}i(Vs,"normalizeIncomingRequestHeaders");var We=ye("zuplo:runtime"),ge=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;We("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(We("Gateway.initialize"),!n.#e){let s=await xn.init(o),a=await e(),u={...a,corsPolicies:ws(a.corsPolicies)},c=new n(u,t,s,r);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){We("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[mt,fn,he];setupRoutes=i(()=>{We("Gateway.setupRoutes");let e=this.routeData,t=new vn;if(e.routes.length===0)return dn(t,this),Do(t,this),No(t,this),Rs(t,this),t;let{enabled:o,version:r}=this.runtimeSettings.developerPortal;o&&(r==="zudoku"?(Ms(t,this),dn(t,this)):r==="legacy"&&(Ns(t,this),_s(t,this))),dn(t,this),Do(t,this),No(t,this);for(let s of Ue)s instanceof Se&&s.registerRoutes(t,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#o,handler:a,gateway:this}),c=new Ge(s);t.addRoute(c,u.execute)}),Ps(t,this),t},"setupRoutes");errorHandler(e,t,o,r){We("Gateway.internalErrorResponse"),t.log.error(o,r);let s={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy)if(r instanceof k&&r.extensionMembers)s=r.extensionMembers;else if(r.cause){let a=rt(r.cause);"stack"in a&&(a.stack=zo(a.stack)),s={cause:a}}else{let a=rt(r);"stack"in a&&(a.stack=zo(a.stack)),s={cause:a}}return E.internalServerError(e,t,{detail:r.message,...s})}async handleRequest(e,t){let o=e.headers.get(lt)??e.headers.get(Hi)??crypto.randomUUID(),r=e.headers.get(et);Gs(t);let s=Vs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(lt,o);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let A=new Headers(a.headers);A.set(io,"true"),a=new Request(a,{headers:A,body:null})}let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:h}=this.#t.createRequestLoggers(o,r,t,d,a,l.routeConfiguration),y=new On(e.headers),C=new te(a,{params:l.params}),P=new Sn({logger:p,route:l.routeConfiguration,requestId:o,event:t,custom:d,incomingRequestProperties:y}),S=Cn.context.getStore();S&&(S.context=P);let N=l.routeConfiguration.raw();wc.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[Ze.RoutePathPattern]:P.route.pathPattern,[Ze.RouteOperationId]:N.operationId,[Ze.RouteTrace]:N["x-zuplo-trace"],[Ze.RouteSystem]:dt(u)?!0:void 0}),Ie.initialize(P,C);try{if(Q.addLogger(P,h),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(u):!u.pathname.startsWith("/__zuplo")){let Z=await cs(C,P);if(Z instanceof Response)return Z;{let v=Ie.getContextExtensions(P);C=Z,v.latestRequest=C}}dt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let A=l.executableHandler;Rc(A,l,a),We("Gateway.handleRequest - call user handler");let F=await A(C,P);if(We("Gateway.handleRequest - user handler"),!(F instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof F}`);if(F.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let z;if(F.headers.get(lt)===null&&!F.webSocket){let Z=new Headers(F.headers);Z.set(lt,o),z=new Response(F.body,{status:F.status,statusText:F.statusText,headers:Z,cf:F.cf})}else z=F;return z}catch(A){return A instanceof k?(p.error(A),h.warn(A)):h.error(A),await this.errorHandler(C,P,"Error executing handler",A)}}};function Rc(n,e,t){if(We("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Rc,"checkHandler");var Ws=i(async(n,e,t)=>{let o=ge.instance.routeData.policies,r=Ht([n],o);if(r.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy"),Js=i(async(n,e,t,o)=>{let r=ge.instance.routeData.policies,s=$t([n],r);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,o)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(po);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(mo)??void 0}get city(){return this.#e.get(so)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(ao)??this.#e.get(Wi)??void 0}get country(){return this.#e.get(uo)??this.#e.get(Ji)??void 0}get latitude(){return this.#e.get(lo)??this.#e.get(Qi)??void 0}get longitude(){return this.#e.get(co)??this.#e.get(Ki)??void 0}get colo(){return this.#e.get(go)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(fo)??void 0}get metroCode(){return this.#e.get(zi)??this.#e.get(ho)??void 0}get region(){return this.#e.get(Fi)??this.#e.get(yo)??void 0}get regionCode(){return this.#e.get(ji)??this.#e.get(bo)??void 0}get timezone(){return this.#e.get(Gi)??this.#e.get(wo)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Ut=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},qt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ie=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)},"onResponseSendingFinal");onResponseSending=i(async(e,t,o)=>{let r=e;for(let s of this.#n)r=await s(e,t,o);return r},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>Ws(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Js(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ie.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ie.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}};var Pc="Error initializing gateway. Check your configuration for errors or contact support.",Ic="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",nr=class{constructor(e,t,o,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,o)=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await ps(this.runtimeInit)}catch(s){this.handleError(s,Ic,e)}return rs(i(async(s,a)=>{let u;try{u=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,Pc,s)}let c={context:void 0};return Cn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,o)},"requestHandler");handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Ec(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){r+=n[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(o==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Ec,"lexer");function rr(n,e){e===void 0&&(e={});for(var t=Ec(n),o=e.prefixes,r=o===void 0?"./":o,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),h=i(function(j){var x=p(j);if(x!==void 0)return x;var I=t[l],M=I.type,le=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(le,", expected ").concat(j))},"mustConsume"),y=i(function(){for(var j="",x;x=p("CHAR")||p("ESCAPED_CHAR");)j+=x;return j},"consumeText"),C=i(function(j){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),P=i(function(j){var x=u[u.length-1],I=j||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||C(I)?"[^".concat(or(a),"]+?"):"(?:(?!".concat(or(I),")[^").concat(or(a),"])+?")},"safePattern");l<t.length;){var S=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var F=S||"";r.indexOf(F)===-1&&(d+=F,F=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:F,suffix:"",pattern:A||P(F),modifier:p("MODIFIER")||""});continue}var z=S||p("ESCAPED_CHAR");if(z){d+=z;continue}d&&(u.push(d),d="");var Z=p("OPEN");if(Z){var F=y(),v=p("NAME")||"",q=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(q?c++:""),pattern:v&&!q?P(F):q,prefix:F,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(rr,"parse");function Ks(n,e){return xc(rr(n,e),e)}i(Ks,"compile");function xc(n,e){e===void 0&&(e={});var t=Tc(e),o=e.encode,r=o===void 0?function(c){return c}:o,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",C=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!C)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var S=r(h[P],p);if(a&&!u[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var S=r(String(h),p);if(a&&!u[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!y){var N=C?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(xc,"tokensToFunction");function or(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(or,"escapeString");function Tc(n){return n&&n.sensitive?"":"i"}i(Tc,"flags");var vc=ye("zuplo:runtime"),sr=new TextEncoder,Qs={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Cc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],yt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=o,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new ar(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){vc("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=H.fetch(r,s);if(o===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},ar=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:o,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:C,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let S,N;(!c||!l)&&([S,N]=Oc(this.url,this.headers)),this.service=c||S||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(z=>C||!Cc.includes(z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(z=>z+":"+(z==="host"?this.url.host:(this.headers.get(z)||"").replace(/\s+/g," "))).join(`
|
|
89
89
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Xs(this.encodedPath);let F=new Set;this.encodedSearch=[...this.url.searchParams].filter(([z])=>{if(!z)return!1;if(this.service==="s3"){if(F.has(z))return!1;F.add(z)}return!0}).map(z=>z.map(Z=>Xs(encodeURIComponent(Z)))).sort(([z,Z],[v,q])=>z<v?-1:z>v?1:Z<q?-1:Z>q?1:0).map(z=>z.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),o=this.cache.get(t);if(!o){let r=await Jt("AWS4"+this.secretAccessKey,e),s=await Jt(r,this.region),a=await Jt(s,this.service);o=await Jt(a,"aws4_request"),this.cache.set(t,o)}return ir(await Jt(o,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ir(await Ys(await this.canonicalString()))].join(`
|
|
90
90
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
91
91
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
92
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=ir(await Ys(this.body||""))}return e}};async function Jt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?sr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,sr.encode(e))}i(Jt,"hmac");async function Ys(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?sr.encode(n):n)}i(Ys,"hash");function ir(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(ir,"buf2hex");function Xs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Xs,"encodeRfc3986");function Oc(n,e){let{hostname:t,pathname:o}=n,r=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(r||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=o==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Qs?[Qs[s],a]:[s,a]}i(Oc,"guessServiceRegion");function Sc(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Sc,"b64ToUint6");function ea(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),o=t.length,r=e?Math.ceil((o*3+1>>2)/e)*e:o*3+1>>2,s=new Uint8Array(r),a,u,c=0,l=0;for(let d=0;d<o;d++)if(u=d&3,c|=Sc(t.charCodeAt(d))<<6*(3-u),u===3||o-d===1){for(a=0;a<3&&l<r;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ea,"base64Decode");function Sn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Sn,"uint6ToB64");function ta(n){let e=2,t="",o=n.length,r=0;for(let s=0;s<o;s++)e=s%3,r|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(Sn(r>>>18&63),Sn(r>>>12&63),Sn(r>>>6&63),Sn(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ta,"base64Encode");function bt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(bt,"numberToString");function Ac(n){let e=n.getTimezoneOffset(),t=Math.abs(e),o=e>0?"-":"+",r=bt(Math.floor(t/60)),s=bt(t%60);return`${o}${r}${s}`}i(Ac,"getCLFOffset");function ur(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=bt(n.getDate()),o=e[n.getMonth()],r=n.getFullYear(),s=bt(n.getHours()),a=bt(n.getMinutes()),u=bt(n.getSeconds()),c=Ac(n);return`${t}/${o}/${r}:${s}:${a}:${u} ${c}`}i(ur,"toCLFDate");var na=ye("zuplo:runtime"),kc="X-Amzn-Trace-Id",Lc="x-amzn-errortype",oa=[],_c=i(async(n,e,t)=>{let o=t;for await(let r of oa)o=await r(n,e,t);return o},"onSendingAwsLambdaEvent"),Te=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(kc)??void 0,this.errorType=t.get(Lc)??void 0}},Nc={addSendingAwsLambdaEventHook:i(n=>{oa.push(n)},"addSendingAwsLambdaEventHook")};async function Dc(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:o,region:r,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!o)throw new m("secretAccessKey is not set in the handler options");if(!r)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new yt({accessKeyId:t,secretAccessKey:o}),d=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(na(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Zc(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,C;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?C=qc(n,e):C=await Uc(n,e,{useAwsResourcePathStyle:u}),na("Calling onSendingAwsLambdaEvent hook");let P=await _c(n,e,C);P.body=p,P.isBase64Encoded=h;let S=await l.fetch(d,{body:JSON.stringify(P)});try{return Mc(S)}catch(N){if(N instanceof Te){let A=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return E.internalServerError(n,e,void 0,A)}throw N}}i(Dc,"awsLambdaHandler");async function Mc(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[r,s]of Object.entries(e.headers))t.set(r,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let o;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);o=ea(e.body)}else"body"in e&&typeof e.body=="string"?o=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?o=JSON.stringify(e.body):o=null;if(o!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let r=new Blob([o]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));o=await new Response(r).arrayBuffer()}return new Response(o,{headers:t,status:e.statusCode})}i(Mc,"getResponse");async function Uc(n,e,{useAwsResourcePathStyle:t}){let o={},r={};n.headers.forEach((l,d)=>{o[d]=l,r[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:o,multiValueHeaders:r,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ur(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:$c(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Uc,"buildEventVersion1");function qc(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let o=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:o.pathname,rawQueryString:o.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:o.hostname,domainPrefix:null,http:{method:n.method,path:o.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:ur(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(qc,"buildEventVersion2");async function Zc(n,{binaryMediaTypes:e}){let t,o=!1,r=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&r&&Hc(e,r)){let s=await n.arrayBuffer();t=ta(new Uint8Array(s)),o=!0}else t=await n.clone().text();return[t,o]}i(Zc,"getBodyResult");function Hc(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(o=>o==="*/*"?!0:o.toLowerCase()===t)>-1}i(Hc,"matchesContentType");function $c(n,e=!1){if(!e)return n;let t=rr(n),o=Ks(n),r={};return t.forEach(s=>{typeof s=="string"?r[s]=`{${s}}`:r[s.name]=`{${s.name}}`}),o(r)}i($c,"getResourcePath");var Fc=[502,503,504];async function wt(n,e){if(Fc.includes(n.status)){let t=Q.getLogger(e),r=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:r,headers:s})}}i(wt,"logBadGatewayResponses");var cr;function Je(n){if(cr===void 0){let t=f.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),cr=t}return n.log[cr]}i(Je,"getHandlerUserLogFunction");async function jc(n,e){g("handler.open-api");let t=f.instance.build.BUILD_ID,{buildAssetsUrl:o}=f.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=zc(s);if(!a.isValid)throw new m(a.error);let u;f.instance.isLocalDevelopment?u=`${o}/${s.substring(1)}`:u=`${o}/${t}${s.substring(1)}`;let c=await H.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return E.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return wt(l,e),l}i(jc,"openApiSpecHandler");var zc=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Bc(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let o=t.status??302;return new Response(null,{status:o,headers:{location:t.location}})}i(Bc,"redirectHandler");async function Gc(n){if(g("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new m("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,f.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${f.instance.authApiJWT}`),H.fetch(e,{method:n.method,headers:t,body:n.body})}i(Gc,"zuploServiceProxy");function Vc(n,e){let t=n.endsWith("/"),o=e.startsWith("/");return t&&o?`${n.substring(0,n.length-1)}${e}`:!t&&!o?`${n}/${e}`:`${n}${e}`}i(Vc,"join");async function Wc(n,e){g("handler.url-forward");let t=Je(e),o=e.route.handler.options,r=o.forwardSearch!==!1;if(!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=o.__rewriteFunction(n,s),c=Vc(u,a.pathname),l=r?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),wt(p,e),p}i(Wc,"urlForwardHandler");var Jc=i((n,e)=>{let t=new URL(n),o=new URL(e);for(let[r,s]of o.searchParams.entries())t.searchParams.append(r,s);return t.toString()},"addQuery");async function Kc(n,e){g("handler.url-rewrite");let t=Je(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=o.__rewriteFunction(n,a),c=r?Jc(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),wt(d,e),d}i(Kc,"urlRewriteHandler");async function Qc(n,e){g("handler.websocket");let t=e.route.handler.options,o=Je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return E.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Qc,"webSocketHandler");var lr=i((n,e)=>n.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${r+1}, export name: ${o.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ra=i(async(n,e,t,o,r,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function ia(n,e,t,o,r){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{o.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ra(c,n,e,t,o,r);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(o.log.error);o.waitUntil(u)}catch(a){o.log.error(a)}})}i(ia,"wireUpListeners");async function Yc(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,o=Je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return E.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let S=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${S}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let C=t.policies&&t.policies.inbound?lr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?lr(t.policies.outbound,"outbound"):[];return ia(p,y,n,e,C),ia(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Yc,"webSocketPipelineHandler");var dr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new pr(this.options)}},pr=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#o=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#r,"custom.environmentType":this.#o,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await ne({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await ne({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("dyna-trace-log-transport",10,this.#i)};var mr=class extends fe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new fr(this.options)}},gr=class{static{i(this,"LokiStream")}constructor(e,t,o,r,s,a){this.level=e,this.environment=t,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Xc(n,e){return btoa(`${n}:${e}`)}i(Xc,"createBasicDigest");var fr=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#o=Xc(e.username,e.password),this.#i=f.instance.loggingEnvironmentType,this.#s=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=new gr(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s={stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(o=>{let r=t.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},t.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let o=await H.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#o}`}});o.ok||await ne({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await ne({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("loki-log-transport",10,this.#u)};var hr=class extends fe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new yr(this.options)}},yr=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#n=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#t=f.instance.deploymentName}#e;#t;#n;#o;#r;#i;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#o,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(r=>JSON.stringify(r)).join(`
|
|
92
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=ir(await Ys(this.body||""))}return e}};async function Jt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?sr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,sr.encode(e))}i(Jt,"hmac");async function Ys(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?sr.encode(n):n)}i(Ys,"hash");function ir(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(ir,"buf2hex");function Xs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Xs,"encodeRfc3986");function Oc(n,e){let{hostname:t,pathname:o}=n,r=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(r||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=o==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Qs?[Qs[s],a]:[s,a]}i(Oc,"guessServiceRegion");function Sc(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Sc,"b64ToUint6");function ea(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),o=t.length,r=e?Math.ceil((o*3+1>>2)/e)*e:o*3+1>>2,s=new Uint8Array(r),a,u,c=0,l=0;for(let d=0;d<o;d++)if(u=d&3,c|=Sc(t.charCodeAt(d))<<6*(3-u),u===3||o-d===1){for(a=0;a<3&&l<r;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ea,"base64Decode");function An(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(An,"uint6ToB64");function ta(n){let e=2,t="",o=n.length,r=0;for(let s=0;s<o;s++)e=s%3,r|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(An(r>>>18&63),An(r>>>12&63),An(r>>>6&63),An(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ta,"base64Encode");function bt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(bt,"numberToString");function Ac(n){let e=n.getTimezoneOffset(),t=Math.abs(e),o=e>0?"-":"+",r=bt(Math.floor(t/60)),s=bt(t%60);return`${o}${r}${s}`}i(Ac,"getCLFOffset");function ur(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=bt(n.getDate()),o=e[n.getMonth()],r=n.getFullYear(),s=bt(n.getHours()),a=bt(n.getMinutes()),u=bt(n.getSeconds()),c=Ac(n);return`${t}/${o}/${r}:${s}:${a}:${u} ${c}`}i(ur,"toCLFDate");var na=ye("zuplo:runtime"),kc="X-Amzn-Trace-Id",Lc="x-amzn-errortype",oa=[],_c=i(async(n,e,t)=>{let o=t;for await(let r of oa)o=await r(n,e,t);return o},"onSendingAwsLambdaEvent"),Te=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(kc)??void 0,this.errorType=t.get(Lc)??void 0}},Nc={addSendingAwsLambdaEventHook:i(n=>{oa.push(n)},"addSendingAwsLambdaEventHook")};async function Dc(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:o,region:r,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!o)throw new m("secretAccessKey is not set in the handler options");if(!r)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new yt({accessKeyId:t,secretAccessKey:o}),d=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(na(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Zc(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,C;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?C=qc(n,e):C=await Uc(n,e,{useAwsResourcePathStyle:u}),na("Calling onSendingAwsLambdaEvent hook");let P=await _c(n,e,C);P.body=p,P.isBase64Encoded=h;let S=await l.fetch(d,{body:JSON.stringify(P)});try{return Mc(S)}catch(N){if(N instanceof Te){let A=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return E.internalServerError(n,e,void 0,A)}throw N}}i(Dc,"awsLambdaHandler");async function Mc(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[r,s]of Object.entries(e.headers))t.set(r,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let o;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);o=ea(e.body)}else"body"in e&&typeof e.body=="string"?o=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?o=JSON.stringify(e.body):o=null;if(o!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let r=new Blob([o]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));o=await new Response(r).arrayBuffer()}return new Response(o,{headers:t,status:e.statusCode})}i(Mc,"getResponse");async function Uc(n,e,{useAwsResourcePathStyle:t}){let o={},r={};n.headers.forEach((l,d)=>{o[d]=l,r[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:o,multiValueHeaders:r,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ur(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:$c(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Uc,"buildEventVersion1");function qc(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let o=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:o.pathname,rawQueryString:o.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:o.hostname,domainPrefix:null,http:{method:n.method,path:o.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:ur(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(qc,"buildEventVersion2");async function Zc(n,{binaryMediaTypes:e}){let t,o=!1,r=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&r&&Hc(e,r)){let s=await n.arrayBuffer();t=ta(new Uint8Array(s)),o=!0}else t=await n.clone().text();return[t,o]}i(Zc,"getBodyResult");function Hc(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(o=>o==="*/*"?!0:o.toLowerCase()===t)>-1}i(Hc,"matchesContentType");function $c(n,e=!1){if(!e)return n;let t=rr(n),o=Ks(n),r={};return t.forEach(s=>{typeof s=="string"?r[s]=`{${s}}`:r[s.name]=`{${s.name}}`}),o(r)}i($c,"getResourcePath");var Fc=[502,503,504];async function wt(n,e){if(Fc.includes(n.status)){let t=Q.getLogger(e),r=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:r,headers:s})}}i(wt,"logBadGatewayResponses");var cr;function Je(n){if(cr===void 0){let t=f.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),cr=t}return n.log[cr]}i(Je,"getHandlerUserLogFunction");async function jc(n,e){g("handler.open-api");let t=f.instance.build.BUILD_ID,{buildAssetsUrl:o}=f.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=zc(s);if(!a.isValid)throw new m(a.error);let u;f.instance.isLocalDevelopment?u=`${o}/${s.substring(1)}`:u=`${o}/${t}${s.substring(1)}`;let c=await H.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return E.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return wt(l,e),l}i(jc,"openApiSpecHandler");var zc=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Bc(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let o=t.status??302;return new Response(null,{status:o,headers:{location:t.location}})}i(Bc,"redirectHandler");async function Gc(n){if(g("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new m("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,f.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${f.instance.authApiJWT}`),H.fetch(e,{method:n.method,headers:t,body:n.body})}i(Gc,"zuploServiceProxy");function Vc(n,e){let t=n.endsWith("/"),o=e.startsWith("/");return t&&o?`${n.substring(0,n.length-1)}${e}`:!t&&!o?`${n}/${e}`:`${n}${e}`}i(Vc,"join");async function Wc(n,e){g("handler.url-forward");let t=Je(e),o=e.route.handler.options,r=o.forwardSearch!==!1;if(!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=o.__rewriteFunction(n,s),c=Vc(u,a.pathname),l=r?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),wt(p,e),p}i(Wc,"urlForwardHandler");var Jc=i((n,e)=>{let t=new URL(n),o=new URL(e);for(let[r,s]of o.searchParams.entries())t.searchParams.append(r,s);return t.toString()},"addQuery");async function Kc(n,e){g("handler.url-rewrite");let t=Je(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=o.__rewriteFunction(n,a),c=r?Jc(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),wt(d,e),d}i(Kc,"urlRewriteHandler");async function Qc(n,e){g("handler.websocket");let t=e.route.handler.options,o=Je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return E.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Qc,"webSocketHandler");var lr=i((n,e)=>n.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${r+1}, export name: ${o.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ra=i(async(n,e,t,o,r,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function ia(n,e,t,o,r){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{o.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ra(c,n,e,t,o,r);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(o.log.error);o.waitUntil(u)}catch(a){o.log.error(a)}})}i(ia,"wireUpListeners");async function Yc(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,o=Je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return E.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let S=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${S}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let C=t.policies&&t.policies.inbound?lr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?lr(t.policies.outbound,"outbound"):[];return ia(p,y,n,e,C),ia(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Yc,"webSocketPipelineHandler");var dr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new pr(this.options)}},pr=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#o=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#r,"custom.environmentType":this.#o,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await ne({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await ne({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("dyna-trace-log-transport",10,this.#i)};var mr=class extends fe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new fr(this.options)}},gr=class{static{i(this,"LokiStream")}constructor(e,t,o,r,s,a){this.level=e,this.environment=t,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Xc(n,e){return btoa(`${n}:${e}`)}i(Xc,"createBasicDigest");var fr=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#o=Xc(e.username,e.password),this.#i=f.instance.loggingEnvironmentType,this.#s=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=new gr(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s={stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(o=>{let r=t.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},t.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let o=await H.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#o}`}});o.ok||await ne({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await ne({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("loki-log-transport",10,this.#u)};var hr=class extends fe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new yr(this.options)}},yr=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#n=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#t=f.instance.deploymentName}#e;#t;#n;#o;#r;#i;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#o,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(r=>JSON.stringify(r)).join(`
|
|
93
93
|
`),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&o.set("X-Sumo-Name",this.#i),this.#r&&o.set("X-Sumo-Category",this.#r);try{let r=await H.fetch(this.#e,{method:"POST",body:t,headers:o});r.ok||await ne({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`]},r)}catch{await ne({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("sumo-logic-log-transport",10,this.#s)};var el="d3a5b78f823648f5b1df4fe269d41172",br=class extends fe{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wr(this.options)}},wr=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??el}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#o=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,r])=>({name:o,content:r})))}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=this.buildEntry(e,t);this.batcher.enqueue(o),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let o=qs(e.messages);this.#t?.forEach(s=>{o=o.replaceAll(s[0],s[1])});let r={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#o},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&r.fields.push({name:"environment",content:this.#n}),this.#s&&r.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=Bo(a);u&&r.fields.push({name:s,content:u})}),this.#i&&(r=this.#i(r)),r}#a=i(async e=>{if(e.length!==0)try{let t=await H.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await ne({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await ne({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("vmware-log-insights-log-transport",10,this.#a)};var Rr=class extends fe{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Pr(this.options)}},Pr=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Y("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});o.ok||await ne({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await ne({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:o,secretAccessKey:r,region:s}){g("logging.aws"),this.awsClient=new yt({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=t,this.region=s,this.environmentType=f.instance.loggingEnvironmentType,this.environment=f.instance.deploymentName}log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().getTime(),message:JSON.stringify({data:He(o),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Ir=new WeakMap,tl={tags:[]},Er=class extends ze{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new xr(this.options)}static setContext(t,o){let r=Ir.get(t);r||(r=tl);let s=Object.assign({...r},o);Ir.set(t,s)}},xr=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#o;#r;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#o=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Y("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()/1e3),r=this.#o.concat(Ir.get(t)?.tags??[]);if(this.#r.country&&r.push(`country:${e.country}`),this.#r.httpMethod&&r.push(`httpMethod:${e.method}`),this.#r.statusCode&&r.push(`statusCode:${e.statusCode}`),this.#r.path){let s=e.systemRouteName||e.routePath;r.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:o,value:e.durationMs}],tags:r}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:r}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:r}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),o=await H.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});o.ok||await ne({level:"error",messages:["Failed to send metrics to DataDog."]},o)}catch{await ne({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Tr=new WeakMap,nl={dimensions:[]},vr=class extends ze{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Cr(this.options)}static setContext(t,o){let r=Tr.get(t);r||(r=nl);let s=Object.assign({...r},o);Tr.set(t,s)}},Cr=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#o=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#o===void 0&&(this.#o=new Y("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(Tr.get(t)?.dimensions??[]);if(this.#n.country&&r.push(`country="${e.country}"`),this.#n.httpMethod&&r.push(`http_method="${e.method}"`),this.#n.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let s=r.join(",");this.#t.latency&&this.#o.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#o.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#o.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${o}`),t.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=e.join(`
|
|
94
94
|
`),o=await H.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});o.ok||await ne({level:"error",messages:["Failed to send metrics to Dynatrace."]},o)}catch{await ne({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Or=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await H.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var Sr=class extends Se{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new Ar(e,this.#e,this.#t)}},sa=i(n=>{let e={};return n.forEach((t,o)=>{e[o]=t}),e},"serializableHeaders"),ol={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ar=class{static{i(this,"AuditPluginImpl")}constructor(e,t,o){this.#t=t;let r={...ol};o?.requestFilter&&(r.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(r,o.include.request),o?.include?.response&&Object.assign(r,o.include.response),this.#e=r,e.addRequestHook(this.#i),this.#n=new Y("audit-log",10,this.#o)}#e;#t;#n;#o=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#r=i(async(e,t,o,r,s,a)=>{try{let u={timestamp:r,durationMs:s,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?sa(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?sa(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),o.waitUntil(this.#n.waitUntilFlushed())}catch(u){o.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let r=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#r(d,a,t,r,l-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(o){return t.log.error(o),e}},"#auditHook")};var kr=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},De=class extends kr{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,o={}){super(o),this.header=e,this.payload=t}};var rl="v1",il=300;async function aa(n,e,t,o=il,r){return await al(n,e,t,o,r),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(aa,"constructEventAsync");function sl(n,e){return`${e.timestamp}.${n}`}i(sl,"makeHMACContent");async function al(n,e,t,o,r){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=ul(n,e,rl),l=/\s/.test(t),d=await pl(sl(a,u),t);return cl(a,s,u,d,o,c,l,r)}i(al,"verifyHeaderAsync");function ul(n,e,t){if(!n)throw new De(e,n,{message:"No webhook payload was provided."});let o=typeof n!="string"&&!(n instanceof Uint8Array),r=new TextDecoder("utf8"),s=n instanceof Uint8Array?r.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new De(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?r.decode(e):e,u=ll(a,t);if(!u||u.timestamp===-1)throw new De(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new De(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:o}}i(ul,"parseEventDetails");function cl(n,e,t,o,r,s,a,u){let c=!!t.signatures.filter(h=>dl(h,o)).length,l=`
|
|
95
95
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
@@ -100,11 +100,11 @@ Signature verification is impossible without access to the original signed mater
|
|
|
100
100
|
`+d}):new De(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
101
101
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
102
102
|
`+l+`
|
|
103
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(cl,"validateComputedSignature");function ll(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(ll,"parseHeader");function dl(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(dl,"secureCompare");async function pl(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Lr[s[u]];return a.join("")}i(pl,"computeHMACSignatureAsync");var Lr=new Array(256);for(let n=0;n<Lr.length;n++)Lr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!nt(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Kt=class extends ue{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await aa(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ua(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}i(ua,"isStripeWebhookEvent");var ml={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new k(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new k(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new k(s)}return r},"getUpcomingInvoice")},An=ml;var _r="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ca="My API Key";async function la({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,_r);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ca,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(la,"createConsumer");async function da({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,_r);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ca,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(da,"createConsumerInvite");async function pa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=f.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,_r);r.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(pa,"deleteConsumer");async function ma({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!pt(p))throw new K("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let C=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await y.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(C,P),new k(`${C} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}i(ma,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!pt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!pt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Pt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Ke="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function kn(n){return n.replaceAll("_","-")}i(kn,"stripeStatusToMeteringStatus");function it(n){return new Date(n*1e3).toISOString()}i(it,"unixTimestampToISOString");async function Nr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await la({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await An.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await da({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=kn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:it(t.data.object.trial_end),trialStartDate:it(t.data.object.trial_start)}),await ma({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await pa({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Ke})}i(Nr,"onCustomerSubscriptionCreated");async function Dr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Pe})}return E.ok(n,e,{title:Ke})}i(Dr,"onCustomerSubscriptionDeleted");async function Mr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=kn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=it(t.data.object.trial_end)),await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await An.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?it(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?it(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Pe})}i(Mr,"onCustomerSubscriptionUpdated");var ga=class extends sn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!gl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ua(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Nr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Mr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Dr(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe})}},"stripeWebhookHandler"),s=Ts({inboundPolicies:[new Kt({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 pe({processors:[he,s],handler:r,gateway:o}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function gl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(gl,"isMetricsRegion");var ha=new WeakMap,fa={},Ur=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ha.set(e,t)}};async function fl(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=Be(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=ha.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=qe(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=fa[t.apiKey];if(!h){let y=t.apiKey,C=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",N=await H.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":C}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${S.message}`),S}}),fa[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(fl,"AmberfloMeteringInboundPolicy");async function st(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(st,"sha256");var ya=new Map;async function se(n,e,t){let o,r=`${n}-${e}`,s=ya.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await st(JSON.stringify({policyName:n,options:t}))}`,ya.set(n,o)),o}i(se,"getPolicyCacheName");var ba="key-metadata-cache-type";function hl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(hl,"getKeyValue");async function qr(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(S=>r.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:S}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=hl(a,r);if(!u||u==="")return s("No key present");let c=await yl(u),l=await se(o,void 0,r),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ba&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let S=await y.text(),N=JSON.parse(S);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${y.status}`)}let C=await y.json(),P={isValid:!0,typeId:ba,user:{sub:C.name,data:C.metadata}};return n.user=P.user,d.put(c,P,r.cacheTtlSeconds),n}i(qr,"ApiKeyInboundPolicy");async function yl(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(yl,"hashValue");var bl=qr;var wa=Symbol("aserto-authz-resource-context"),Zr=class extends ue{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){re.set(e,wa,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let o=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let r=re.get(t,wa),s;r?.policyInstance?s=r.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?qe(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:r?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:r?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:r?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await H.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?o(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),o("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as Rl,jwtVerify as Pa}from"jose";import{createLocalJWKSet as wl}from"jose";var Hr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof $r&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=wl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await H.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Fr("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new It("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new It("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ra(n,e,t){let o=new Hr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(Ra,"createRemoteJWKSet");var It=class extends k{static{i(this,"JWKSError")}},$r=class extends It{static{i(this,"JWKSNoMatchingKey")}},Fr=class extends It{static{i(this,"JWKSTimeout")}};var Ln={},Pl=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Ln[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await se(n,void 0,o),u=new ie(a,e);Ln[o.jwkUrl]=Ra(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else Ln[o.jwkUrl]=Rl(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await Pa(t,Ln[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),Il=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await Pa(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=t.authHeader??"Authorization",s=n.headers.get(r),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Pl(o,e):Il,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(C){let P=new URL(n.url);return"code"in C&&C.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${P.pathname} `,C):e.log.warn(`Invalid token on: ${n.method} ${P.pathname}`,C),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",h=d[p];return h?(n.user={sub:h,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var El=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var _n=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 H.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 jr=class n extends ue{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new _n(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var xl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),C=t.accounts.find(P=>P.username===h&&P.password===y);return C||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 Nn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Nn,"extractDateElements");function Ia(n,e){return new Date(n,e+1,0).getDate()}i(Ia,"getDaysInMonth");function zr(n,e){return n<=e?e-n:6-n+e+1}i(zr,"getDaysBetweenWeekdays");var Dn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Ia(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?zr(d,p):zr(p,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Nn(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Nn(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=Nn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Tl={min:0,max:59},vl={min:0,max:59},Cl={min:0,max:23},Ol={min:1,max:31},Sl={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"}},Al={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},kl={"@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 at(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{at(d,e).forEach(h=>t.add(h))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(at,"parseElement");function Br(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=kl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Dn({seconds:at(t,Tl),minutes:at(o,vl),hours:at(r,Cl),days:at(s,Ol),months:new Set(Array.from(at(a,Sl)).map(c=>c-1)),weekdays:new Set(Array.from(at(u,Al)).map(c=>c%7))})}i(Br,"parseCronExpression");var Gr=class extends ue{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Br(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Br(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Ll=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _l(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(_l,"digestMessage");var Nl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await _l(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Dl(n,e,t,o){g("policy.inbound.caching");let r=await se(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ll.forEach(C=>y.headers.delete(C)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(Dl,"CachingInboundPolicy");var Ml=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ul=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new te(n,{headers:r})},"ClearHeadersInboundPolicy");var ql=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Zl=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Hl=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Mn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Vr=class extends Mn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Wr=class extends Mn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function $l(n,e){if(ys(n))throw new Vr(e)}i($l,"throwIfUndefinedOrNull");function Ea(n,e){if($l(n,e),!Ee(n))throw new Wr(e,"string")}i(Ea,"throwIfNotString");var Jr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},Kr=class{constructor(e,t,o,r){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=o;this.userAgent=r}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:o,requestId:r}){Ea(e,"url");let s=await H.fetch(`${this.clientUrl}${e}`,{method:o,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":r,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await st(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await st(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Qe;function Ye(n,e){if(Qe)return Qe;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Qe=new Jr,Qe;let{authApiJWT:t,redisURL:o}=f.instance;if(!Ee(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(t))throw new K(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(Qe=new Kr(o,t,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!Qe||!Qe.isEnabled())throw new K(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Qe}i(Ye,"getRateLimitClient");var Fl=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 Et(n,e){return{function:Gl(e,"RateLimitInboundPolicy",n),user:zl,ip:jl,all:Bl}[e.rateLimitBy??"ip"]}i(Et,"getRateLimitByFunctions");var jl=i(async n=>({key:`ip-${Fl(n)}`}),"getIP"),zl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Bl=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Gl(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(Gl,"wrapUserFunction");var xt="Retry-After";var xa=ye("zuplo:policies:ComplexRateLimitInboundPolicy"),Qr=Symbol("complex-rate-limit-counters"),Yr=class n extends ue{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=re.get(e,Qr)??{};Object.assign(o,t),re.set(e,Qr,t)}static getIncrements(e){return re.get(e,Qr)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Ye(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[xt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Et(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let S=n.getIncrements(t);xa(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:h,increment:S[F]??0})),A=s.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(S){r.error(S),t.log.error(S)}});let y=Object.entries(p).map(([S,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:h,limit:N})),C=await s.multiCount(y,t.requestId);return Vl(C,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;xa(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Vl(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Vl,"findOverLimits");var Wl=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=ge.instance,s=Ht(t.policies,r?.routeData.policies);return Ho(s)(n,e)},"CompositeInboundPolicy");var Jl=i(async(n,e,t,o,r)=>{if(g("policy.outbound.composite"),!o.policies||o.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=ge.instance,a=$t(o.policies,s?.routeData.policies);return $o(a)(n,e,t)},"CompositeOutboundPolicy");var Kl=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return E.unauthorized(n,e,{detail:"No authorization header"});let s=Ql(r);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(o,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await H.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Ql(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Ql,"getToken");var Yl=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var Xl=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Tt="__unknown__",ed=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Ct(t.allow?.countries,"allow.countries",o),regionCodes:Ct(t.allow?.regionCodes,"allow.regionCode",o),asns:Ct(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Ct(t.block?.countries,"block.countries",o),regionCodes:Ct(t.block?.regionCodes,"block.regionCode",o),asns:Ct(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Tt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Tt,u=e.incomingRequestProperties.asn?.toString()??Tt,c=r.ignoreUnknown&&s===Tt,l=r.ignoreUnknown&&a===Tt,d=r.ignoreUnknown&&u===Tt,p=r.allow.countries,h=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return vt(n,e,o,s,a,u);let C=r.block.countries,P=r.block.regionCodes,S=r.block.asns;return C.length>0&&C.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?vt(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function vt(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(vt,"blockedResponse");function Ct(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ct,"toLowerStringArray");var td=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var nd=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return Xr(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return Xr(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ta(a[u])}else return a.length>0?Ta(a[0]):Xr(o,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ta(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(Ta,"generateResponse");var Xr=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return E.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var od="Incoming",rd={logRequestBody:!0,logResponseBody:!0};function va(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(va,"headersToObject");function Ca(){return new Date().toISOString()}i(Ca,"timestamp");var ei=new WeakMap,id={};function sd(n,e){let t=ei.get(n);t||(t=id);let o=Object.assign({...t},e);ei.set(n,o)}i(sd,"setMoesifContext");async function Oa(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(Oa,"readBody");var ad={},ti;function Sa(){if(!ti)throw new k("Invalid State - no _lastLogger");return ti}i(Sa,"getLastLogger");function ud(n){let e=ad[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);Sa().debug("posting",o);let r=await H.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||Sa().error({status:r.status,body:await r.text()})})),e}i(ud,"getDispatcher");async function cd(n,e,t,o){g("policy.inbound.moesif-analytics"),ti=e.log;let r=Ca(),s=Object.assign(rd,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await Oa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=ud(s.applicationId),d=n.headers.get("true-client-ip"),p=ei.get(e)??{},h={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:va(n.headers)},y=s.logResponseBody?await Oa(u,e):void 0,C={time:Ca(),status:u.status,headers:va(u.headers),body:y},P={request:h,response:C,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:od};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(cd,"MoesifInboundPolicy");async function Aa(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await H.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Aa,"loadSubscription");async function ka(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await H.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(ka,"consumeSubcriptionQuotas");var ld=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Un(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Un,"validateMeters");function La(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=ot(n),o=[];for(let r of t)ld.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(La,"parseAllowedSubscriptionStatuses");function _a(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(_a,"compareMeters");var ni=class extends ue{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return re.get(e,_t)}static setMeters(e,t){Un(t,"setMeters");let o=re.get(e,Nt)??{};Object.assign(o,t),re.set(e,Nt,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=Be(this.options.meterOnStatusCodes),s=re.get(t,Nt),a={...this.options.meters,...s};Un(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=La(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,N)=>{let A=re.get(N,_t);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=re.get(N,Nt),Z={...this.options.meters,...z};if(Un(Z,this.policyName),r.includes(P.status)&&A&&Z){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(Z)} on response status '${P.status}'`);let{metersInSubscription:v,metersNotInSubscription:q}=_a(A.meters,Z);if(q&&Object.keys(q).length>0){let V=Object.keys(q);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await ka(N,A.id,this.policyName,this.options.bucketId,v)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Aa(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),re.set(t,_t,p));let h=re.get(t,_t);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let C=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(C.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${C.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${C.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!o)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function qn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await be({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(qn,"getClientCredentialsAccessToken");var Ot=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},Zn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new m("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await H.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Ot("unknown",`Unknown error. Status: ${c.status}`):new Ot(l.code,l.message)}return c.json()}};function Qt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Qt,"setHeaderIfNotSet");var Na="X-OpenFGA-Client-Method",Da="X-OpenFGA-Client-Bulk-Request-Id",Yt=class extends Zn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Qt(o,Na,"BatchCheck"),Qt(o,Da,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Ot)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Qt(c,Na,"ListRelations"),Qt(c,Da,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Ma=Symbol("openfga-authz-context-data"),St=class extends ue{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];re.set(e,Ma,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Yt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=re.get(t,Ma);if(!r||r.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new K(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await qn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ua=["us1","eu1","au1"],oi=class extends St{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ua.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ua.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var dd=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var ri=class extends St{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as pd}from"jose";var ii,md=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ii)try{ii=await pd(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:ii,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var si="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",qa="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ai=class n extends ue{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=gd(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=fd(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Ye(this.policyName,r),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),o&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let C=[],P="";if(Object.entries(y).forEach(([S,N])=>{o&&(P+=`${S} - allowed: ${N} value: ${h.meters[S]??0}
|
|
104
|
-
`),(h.meters[S]??0)>=N&&C.push(S)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",P),C.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${C.join(", ")}'`});t.addResponseSendingFinalHook(async(S,N,A)=>{if(o&&A.log.debug(`QuotaInboundPolicy: backend response - ${S.status}: ${S.statusText}`),!s.quotaOnStatusCodes.includes(S.status))return;let F=re.get(A,si),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};o&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let Z=p.setQuota(d,z,A.requestId);A.waitUntil(Z)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let o=re.get(e,si)??{};Object.assign(o,t),re.set(e,si,o)}static getUsage(e,t){let o=re.get(e,`${qa}-${t}`);if(o===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return o}static#e(e,t,o){re.set(e,`${qa}-${t}`,o)}};function gd(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Be(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}i(gd,"validateAndParseOptions");function fd(n,e){return encodeURIComponent(`${e}-${n}`)}i(fd,"processKey");var Za=ye("zuplo:policies:RateLimitInboundPolicy"),Ha=i(async(n,e,t,o)=>{let r=Q.getLogger(e),s=i((Z,v)=>{let q={};return(!Z||Z==="retry-after")&&(q[xt]=v.toString()),E.tooManyRequests(n,e,void 0,q)},"rateLimited"),u=await Et(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Ye(o,r),C=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${o}/${c}`,P=await se(o,void 0,t),S=new ie(P,e),N=h.getCountAndUpdateExpiry(C,d,e.requestId),A;i(async()=>{let Z=await N;if(Z.count>l){let v=Date.now()+Z.ttlSeconds*1e3;S.put(C,v,Z.ttlSeconds),Za(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${C}' (async mode)`),A=s(p,Z.ttlSeconds)}},"asyncCheck")();let z=await S.get(C);if(z!==void 0&&z>Date.now()){Za(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${C}' (async mode)`);let Z=Math.round((z-Date.now())/1e3);return s(p,Z)}return e.addResponseSendingHook(async Z=>A??Z),n},"AsyncRateLimitInboundPolicyImpl");var $a=ye("zuplo:policies:RateLimitInboundPolicy"),hd="strict",Fa=i(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??hd)==="async")return Ha(n,e,t,o);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[xt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Et(o,t)(n,e,o),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,C=t.headerMode??"retry-after",P=Ye(o,a),N=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${o}/${p}`,A=await P.getCountAndUpdateExpiry(N,y,e.requestId);return A.count>h?($a(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(C,A.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;$a(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ui;function ja(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}i(ja,"headersToNameValuePairs");function yd(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}i(yd,"queryToNameValueParis");function bd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(bd,"parseIntOrUndefined");var za={};async function wd(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return ui||(ui={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?qe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?qe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:ui,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ja(n.headers),queryString:yd(n.query)},response:{status:a.status,statusText:a.statusText,headers:ja(a.headers),content:{size:bd(n.headers.get("content-length"))}}}]}}},d=za[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",C=await H.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});C.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${C.status}: '${await C.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),za[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(wd,"ReadmeMetricsInboundPolicy");var Rd=i(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return r.forEach(u=>{s.delete(u)}),new te(n,{headers:s})},"RemoveHeadersInboundPolicy");var Pd=i(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let s=o?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Id=i(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return r.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Ed=i(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),s=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(s,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ba=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),xd=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Ba():s&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?Ba():n},"RequestSizeLimitInboundPolicy");var At=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),kt=i((n,e,t,o,r)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=jn(t,o,r,c.name),p=ge.instance.schemaValidator[d],h=p(e[c.name]),y=ci(p.errors);h||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),ci=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 Ga(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let C=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=E.badRequest(e,n,{detail:`${C}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",C,[o],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,C=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?C:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=zn(n.route.path,e.method,r),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,C=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?C:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=ci(l),h=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[o],p),Le(t.validateBody))return h}i(Ga,"handleBodyValidation");function Va(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=At(n),s=kt(r.filter(a=>a.in==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Va,"handleHeadersValidation");function Wa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=At(n),r=kt(o.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(Wa,"handlePathParameterValidation");function Ja(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=At(n),r=kt(o.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(Ja,"handleQueryParameterValidation");var Ka=i(async(n,e,t)=>{g("policy.inbound.request-validation");let o=Ja(e,n,t);if(o!==void 0||(o=Wa(e,n,t),o!==void 0)||(o=Va(e,n,t),o!==void 0))return o;let r=await Ga(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),Td=Ka;var vd=i(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Cd=i(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var Od=i(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(n,{headers:s})},"SetHeadersInboundPolicy");var Sd=i(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let s=o.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Ad=i(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),n)},"SetQueryParamsInboundPolicy");var kd=i(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var Ld=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),_d=i(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await Ld(t.sleepInMs),n},"SleepInboundPolicy");var Nd=i(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,r,o);if(s instanceof Response)return s;if(!(s instanceof te))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${o}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Dd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await se(o,void 0,t),s=new ie(r,e),a=await s.get(o);if(!a){let u=await Md(t,e);s.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Md(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Md,"getAccessToken");var Qa="https://accounts.google.com/o/oauth2/token",li,Ud=i(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),li||(li=await xe.init(t.serviceAccountJson));let r={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(o,void 0,t),a=new ie(s,e),u=await a.get(o);if(!u){let c=await Ne({serviceAccount:li,audience:Qa,payload:r}),l=await wn(Qa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var qd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Zd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],di,Hd=i(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Zd.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}di||(di=await xe.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=qe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${o}`);let a=await se(o,void 0,t),u=new ie(a,e),c={uid:s,claims:r},l=await st(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:di,audience:qd,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Fs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let o=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await se("zuplo-token",void 0,t),s=await o.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await qn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var Ya="service-account-id-token",pi=class extends ue{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new Fe(this.cacheName):o=new ie(this.cacheName,t);let r=await o.get(Ya);if(!r){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Xt.getIDToken(t,{audience:s}),u=await Hs(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 $s({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");r=l.token,o.put(Ya,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${r}`),e}};var mi,$d=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),mi||(mi=await xe.init(t.serviceAccountJson));let r=await Ne({serviceAccount:mi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var Xa="https://www.googleapis.com/oauth2/v4/token",gi,Fd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),gi||(gi=await xe.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await se(o,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new ie(s,e);let u=await a.get(o);if(!u){let c=await Ne({serviceAccount:gi,audience:Xa,payload:r}),l=await wn(Xa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var jd=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return n;let{errors:a}=t.validator.default;if(!a)throw new K("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return E.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var eu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=i((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),r=i((P,S)=>i(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(A,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,F,z){return A},"updateTag")},N=o(function(A){return Object.assign({},S,A)},"buildOptions");P.buildOptions=N,P.defaultOptions=S}}),a=r({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+S+"]["+N+"]*",F=new RegExp("^"+A+"$"),z=o(function(v,q){let V=[],j=q.exec(v);for(;j;){let x=[];x.startIndex=q.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=q.exec(v)}return V},"getAllMatches"),Z=o(function(v){let q=F.exec(v);return!(q===null||typeof q>"u")},"isName");P.isExist=function(v){return typeof v<"u"},P.isEmptyObject=function(v){return Object.keys(v).length===0},P.merge=function(v,q,V){if(q){let j=Object.keys(q),x=j.length;for(let I=0;I<x;I++)V==="strict"?v[j[I]]=[q[j[I]]]:v[j[I]]=q[j[I]]}},P.getValue=function(v){return P.isExist(v)?v:""},P.isName=Z,P.getAllMatches=z,P.nameRegexp=A}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var N=class{static{i(this,"XmlNode")}static{o(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,F){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:F})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};S.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var N=a();function A(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,ve="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&Z(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&v(x,I))I+=8;else if(J&&q(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,ve=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:ve+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(A,"readDocType"),o(A,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),o(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),o(z,"isComment");function Z(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="N"&&x[I+4]==="T"&&x[I+5]==="I"&&x[I+6]==="T"&&x[I+7]==="Y"}i(Z,"isEntity"),o(Z,"isEntity");function v(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(v,"isElement"),o(v,"isElement");function q(x,I){return x[I+1]==="!"&&x[I+2]==="A"&&x[I+3]==="T"&&x[I+4]==="T"&&x[I+5]==="L"&&x[I+6]==="I"&&x[I+7]==="S"&&x[I+8]==="T"}i(q,"isAttlist"),o(q,"isAttlist");function V(x,I){return x[I+1]==="!"&&x[I+2]==="N"&&x[I+3]==="O"&&x[I+4]==="T"&&x[I+5]==="A"&&x[I+6]==="T"&&x[I+7]==="I"&&x[I+8]==="O"&&x[I+9]==="N"}i(V,"isNotation"),o(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),o(j,"validateEntityName"),S.exports=A}}),l=r({"../../node_modules/strnum/strnum.js"(P,S){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(v,q={}){if(q=Object.assign({},F,q),!v||typeof v!="string")return v;let V=v.trim();if(q.skipLike!==void 0&&q.skipLike.test(V))return v;if(q.hex&&N.test(V))return Number.parseInt(V,16);{let j=A.exec(V);if(j){let x=j[1],I=j[2],M=Z(j[3]),le=j[4]||j[6];if(!q.leadingZeros&&I.length>0&&x&&V[2]!==".")return v;if(!q.leadingZeros&&I.length>0&&!x&&V[1]!==".")return v;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?q.eNotation?J:v:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:v:I?M===X||x+M===X?J:v:V===X||V===x+X?J:v}}else return v}}i(z,"toNumber"),o(z,"toNumber");function Z(v){return v&&v.indexOf(".")!==-1&&(v=v.replace(/0+$/,""),v==="."?v="0":v[0]==="."?v="0"+v:v[v.length-1]==="."&&(v=v.substr(0,v.length-1))),v}i(Z,"trimZeros"),o(Z,"trimZeros"),S.exports=z}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var N=a(),A=u(),F=c(),z=l(),Z=class{static{i(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=v,this.parseXml=I,this.parseTextData=q,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function v(R){let T=Object.keys(R);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:R[B]}}}i(v,"addExternalEntities"),o(v,"addExternalEntities");function q(R,T,L,B,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!B&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(T,R,L,_,D);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?me(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?me(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(q,"parseTextData"),o(q,"parseTextData");function V(R){if(this.options.removeNSPrefix){let T=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(R=L+T[1])}return R}i(V,"resolveNameSpace"),o(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(R,T,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let B=N.getAllMatches(R,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let $=this.resolveNameSpace(B[ee][1]),U=B[ee][4],de=this.options.attributeNamePrefix+$;if($.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 oe=this.options.attributeValueProcessor($,U,T);oe==null?D[de]=U:typeof oe!=typeof U||oe!==U?D[de]=oe: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 ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),o(x,"buildAttributesMap");var I=o(function(R){R=R.replace(/\r\n?/g,`
|
|
105
|
-
`);let T=new A("!xml"),L=T,B="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let $=b(R,">",D,"Closing Tag is not closed."),U=R.substring(D+2,$).trim();if(this.options.removeNSPrefix){let Oe=U.indexOf(":");Oe!==-1&&(U=U.substr(Oe+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&(B=this.saveTextToParentTag(B,L,_));let de=_.substring(_.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let oe=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=$}else if(R[D+1]==="?"){let $=O(R,D,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new A($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,_,$.tagName)),this.addChild(L,U,_)}D=$.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let $=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=R.substring(D+4,$-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=$}else if(R.substr(D+1,2)==="!D"){let $=F(R,D);this.docTypeEntities=$.entities,D=$.i}else if(R.substr(D+1,2)==="!["){let $=b(R,"]]>",D,"CDATA is not closed.")-2,U=R.substring(D+9,$);B=this.saveTextToParentTag(B,L,_);let de=this.parseTextData(U,L.tagname,_,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):L.add(this.options.textNodeName,de),D=$+2}else{let $=O(R,D,this.options.removeNSPrefix),U=$.tagName,de=$.rawTagName,oe=$.tagExp,Oe=$.attrExpPresent,Ei=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let xi=L;if(xi&&this.options.unpairedTags.indexOf(xi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),U!==T.tagname&&(_+=_?"."+U:U),this.isItStopNode(this.options.stopNodes,_,U)){let Ce="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=$.closeIndex;else{let
|
|
103
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(cl,"validateComputedSignature");function ll(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(ll,"parseHeader");function dl(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(dl,"secureCompare");async function pl(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Lr[s[u]];return a.join("")}i(pl,"computeHMACSignatureAsync");var Lr=new Array(256);for(let n=0;n<Lr.length;n++)Lr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!nt(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Kt=class extends ue{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await aa(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ua(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}i(ua,"isStripeWebhookEvent");var ml={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new k(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new k(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await H.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new k(s)}return r},"getUpcomingInvoice")},kn=ml;var _r="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ca="My API Key";async function la({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,_r);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ca,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(la,"createConsumer");async function da({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,_r);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ca,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(da,"createConsumerInvite");async function pa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=f.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,_r);r.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(pa,"deleteConsumer");async function ma({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!pt(p))throw new K("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let C=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await y.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(C,P),new k(`${C} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}i(ma,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!pt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!pt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Pt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Ke="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Ln(n){return n.replaceAll("_","-")}i(Ln,"stripeStatusToMeteringStatus");function it(n){return new Date(n*1e3).toISOString()}i(it,"unixTimestampToISOString");async function Nr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await la({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await kn.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await da({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Ln(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:it(t.data.object.trial_end),trialStartDate:it(t.data.object.trial_start)}),await ma({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await pa({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Ke})}i(Nr,"onCustomerSubscriptionCreated");async function Dr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Pe})}return E.ok(n,e,{title:Ke})}i(Dr,"onCustomerSubscriptionDeleted");async function Mr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=Ln(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=it(t.data.object.trial_end)),await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await kn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?it(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?it(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ke})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Pe})}i(Mr,"onCustomerSubscriptionUpdated");var ga=class extends sn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!gl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ua(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Nr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Mr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Dr(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe})}},"stripeWebhookHandler"),s=Ts({inboundPolicies:[new Kt({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 pe({processors:[he,s],handler:r,gateway:o}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function gl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(gl,"isMetricsRegion");var ha=new WeakMap,fa={},Ur=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ha.set(e,t)}};async function fl(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=Be(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=ha.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=qe(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=fa[t.apiKey];if(!h){let y=t.apiKey,C=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",N=await H.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":C}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${S.message}`),S}}),fa[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(fl,"AmberfloMeteringInboundPolicy");async function st(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(st,"sha256");var ya=new Map;async function se(n,e,t){let o,r=`${n}-${e}`,s=ya.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await st(JSON.stringify({policyName:n,options:t}))}`,ya.set(n,o)),o}i(se,"getPolicyCacheName");var ba="key-metadata-cache-type";function hl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(hl,"getKeyValue");async function qr(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(S=>r.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:S}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=hl(a,r);if(!u||u==="")return s("No key present");let c=await yl(u),l=await se(o,void 0,r),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ba&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let S=await y.text(),N=JSON.parse(S);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${y.status}`)}let C=await y.json(),P={isValid:!0,typeId:ba,user:{sub:C.name,data:C.metadata}};return n.user=P.user,d.put(c,P,r.cacheTtlSeconds),n}i(qr,"ApiKeyInboundPolicy");async function yl(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(yl,"hashValue");var bl=qr;var wa=Symbol("aserto-authz-resource-context"),Zr=class extends ue{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){re.set(e,wa,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let o=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let r=re.get(t,wa),s;r?.policyInstance?s=r.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?qe(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:r?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:r?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:r?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await H.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?o(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),o("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as Rl,jwtVerify as Pa}from"jose";import{createLocalJWKSet as wl}from"jose";var Hr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof $r&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=wl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await H.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Fr("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new It("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new It("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ra(n,e,t){let o=new Hr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(Ra,"createRemoteJWKSet");var It=class extends k{static{i(this,"JWKSError")}},$r=class extends It{static{i(this,"JWKSNoMatchingKey")}},Fr=class extends It{static{i(this,"JWKSTimeout")}};var _n={},Pl=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!_n[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await se(n,void 0,o),u=new ie(a,e);_n[o.jwkUrl]=Ra(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else _n[o.jwkUrl]=Rl(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await Pa(t,_n[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),Il=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await Pa(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=t.authHeader??"Authorization",s=n.headers.get(r),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Pl(o,e):Il,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(C){let P=new URL(n.url);return"code"in C&&C.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${P.pathname} `,C):e.log.warn(`Invalid token on: ${n.method} ${P.pathname}`,C),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",h=d[p];return h?(n.user={sub:h,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var El=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var Nn=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 H.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 jr=class n extends ue{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Nn(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var xl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),C=t.accounts.find(P=>P.username===h&&P.password===y);return C||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 Dn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Dn,"extractDateElements");function Ia(n,e){return new Date(n,e+1,0).getDate()}i(Ia,"getDaysInMonth");function zr(n,e){return n<=e?e-n:6-n+e+1}i(zr,"getDaysBetweenWeekdays");var Mn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Ia(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?zr(d,p):zr(p,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Dn(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Dn(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=Dn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Tl={min:0,max:59},vl={min:0,max:59},Cl={min:0,max:23},Ol={min:1,max:31},Sl={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"}},Al={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},kl={"@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 at(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{at(d,e).forEach(h=>t.add(h))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(at,"parseElement");function Br(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=kl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Mn({seconds:at(t,Tl),minutes:at(o,vl),hours:at(r,Cl),days:at(s,Ol),months:new Set(Array.from(at(a,Sl)).map(c=>c-1)),weekdays:new Set(Array.from(at(u,Al)).map(c=>c%7))})}i(Br,"parseCronExpression");var Gr=class extends ue{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Br(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Br(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Ll=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _l(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(_l,"digestMessage");var Nl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await _l(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Dl(n,e,t,o){g("policy.inbound.caching");let r=await se(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ll.forEach(C=>y.headers.delete(C)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(Dl,"CachingInboundPolicy");var Ml=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ul=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new te(n,{headers:r})},"ClearHeadersInboundPolicy");var ql=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Zl=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Hl=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Un=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Vr=class extends Un{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Wr=class extends Un{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function $l(n,e){if(ys(n))throw new Vr(e)}i($l,"throwIfUndefinedOrNull");function Ea(n,e){if($l(n,e),!Ee(n))throw new Wr(e,"string")}i(Ea,"throwIfNotString");var Jr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},Kr=class{constructor(e,t,o,r){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=o;this.userAgent=r}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:o,requestId:r}){Ea(e,"url");let s=await H.fetch(`${this.clientUrl}${e}`,{method:o,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":r,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await st(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await st(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Qe;function Ye(n,e){if(Qe)return Qe;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Qe=new Jr,Qe;let{authApiJWT:t,redisURL:o}=f.instance;if(!Ee(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(t))throw new K(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(Qe=new Kr(o,t,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!Qe||!Qe.isEnabled())throw new K(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Qe}i(Ye,"getRateLimitClient");var Fl=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 Et(n,e){return{function:Gl(e,"RateLimitInboundPolicy",n),user:zl,ip:jl,all:Bl}[e.rateLimitBy??"ip"]}i(Et,"getRateLimitByFunctions");var jl=i(async n=>({key:`ip-${Fl(n)}`}),"getIP"),zl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Bl=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Gl(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(Gl,"wrapUserFunction");var xt="Retry-After";var xa=ye("zuplo:policies:ComplexRateLimitInboundPolicy"),Qr=Symbol("complex-rate-limit-counters"),Yr=class n extends ue{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=re.get(e,Qr)??{};Object.assign(o,t),re.set(e,Qr,t)}static getIncrements(e){return re.get(e,Qr)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Ye(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[xt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Et(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let S=n.getIncrements(t);xa(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:h,increment:S[F]??0})),A=s.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(S){r.error(S),t.log.error(S)}});let y=Object.entries(p).map(([S,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:h,limit:N})),C=await s.multiCount(y,t.requestId);return Vl(C,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;xa(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Vl(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Vl,"findOverLimits");var Wl=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=ge.instance,s=Ht(t.policies,r?.routeData.policies);return Ho(s)(n,e)},"CompositeInboundPolicy");var Jl=i(async(n,e,t,o,r)=>{if(g("policy.outbound.composite"),!o.policies||o.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=ge.instance,a=$t(o.policies,s?.routeData.policies);return $o(a)(n,e,t)},"CompositeOutboundPolicy");var Kl=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return E.unauthorized(n,e,{detail:"No authorization header"});let s=Ql(r);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(o,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await H.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Ql(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Ql,"getToken");var Yl=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var Xl=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Tt="__unknown__",ed=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Ct(t.allow?.countries,"allow.countries",o),regionCodes:Ct(t.allow?.regionCodes,"allow.regionCode",o),asns:Ct(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Ct(t.block?.countries,"block.countries",o),regionCodes:Ct(t.block?.regionCodes,"block.regionCode",o),asns:Ct(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Tt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Tt,u=e.incomingRequestProperties.asn?.toString()??Tt,c=r.ignoreUnknown&&s===Tt,l=r.ignoreUnknown&&a===Tt,d=r.ignoreUnknown&&u===Tt,p=r.allow.countries,h=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return vt(n,e,o,s,a,u);let C=r.block.countries,P=r.block.regionCodes,S=r.block.asns;return C.length>0&&C.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?vt(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function vt(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(vt,"blockedResponse");function Ct(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ct,"toLowerStringArray");var td=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var nd=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return Xr(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return Xr(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ta(a[u])}else return a.length>0?Ta(a[0]):Xr(o,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ta(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(Ta,"generateResponse");var Xr=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return E.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var od="Incoming",rd={logRequestBody:!0,logResponseBody:!0};function va(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(va,"headersToObject");function Ca(){return new Date().toISOString()}i(Ca,"timestamp");var ei=new WeakMap,id={};function sd(n,e){let t=ei.get(n);t||(t=id);let o=Object.assign({...t},e);ei.set(n,o)}i(sd,"setMoesifContext");async function Oa(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(Oa,"readBody");var ad={},ti;function Sa(){if(!ti)throw new k("Invalid State - no _lastLogger");return ti}i(Sa,"getLastLogger");function ud(n){let e=ad[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);Sa().debug("posting",o);let r=await H.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||Sa().error({status:r.status,body:await r.text()})})),e}i(ud,"getDispatcher");async function cd(n,e,t,o){g("policy.inbound.moesif-analytics"),ti=e.log;let r=Ca(),s=Object.assign(rd,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await Oa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=ud(s.applicationId),d=n.headers.get("true-client-ip"),p=ei.get(e)??{},h={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:va(n.headers)},y=s.logResponseBody?await Oa(u,e):void 0,C={time:Ca(),status:u.status,headers:va(u.headers),body:y},P={request:h,response:C,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:od};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(cd,"MoesifInboundPolicy");async function Aa(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await H.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Aa,"loadSubscription");async function ka(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await H.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(ka,"consumeSubcriptionQuotas");var ld=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function qn(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(qn,"validateMeters");function La(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=ot(n),o=[];for(let r of t)ld.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(La,"parseAllowedSubscriptionStatuses");function _a(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(_a,"compareMeters");var ni=class extends ue{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return re.get(e,_t)}static setMeters(e,t){qn(t,"setMeters");let o=re.get(e,Nt)??{};Object.assign(o,t),re.set(e,Nt,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=Be(this.options.meterOnStatusCodes),s=re.get(t,Nt),a={...this.options.meters,...s};qn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=La(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,N)=>{let A=re.get(N,_t);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=re.get(N,Nt),Z={...this.options.meters,...z};if(qn(Z,this.policyName),r.includes(P.status)&&A&&Z){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(Z)} on response status '${P.status}'`);let{metersInSubscription:v,metersNotInSubscription:q}=_a(A.meters,Z);if(q&&Object.keys(q).length>0){let V=Object.keys(q);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await ka(N,A.id,this.policyName,this.options.bucketId,v)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Aa(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),re.set(t,_t,p));let h=re.get(t,_t);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let C=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(C.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${C.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${C.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!o)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Zn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await be({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(Zn,"getClientCredentialsAccessToken");var Ot=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},Hn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new m("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await H.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Ot("unknown",`Unknown error. Status: ${c.status}`):new Ot(l.code,l.message)}return c.json()}};function Qt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Qt,"setHeaderIfNotSet");var Na="X-OpenFGA-Client-Method",Da="X-OpenFGA-Client-Bulk-Request-Id",Yt=class extends Hn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Qt(o,Na,"BatchCheck"),Qt(o,Da,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Ot)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Qt(c,Na,"ListRelations"),Qt(c,Da,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Ma=Symbol("openfga-authz-context-data"),St=class extends ue{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];re.set(e,Ma,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Yt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=re.get(t,Ma);if(!r||r.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new K(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await Zn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ua=["us1","eu1","au1"],oi=class extends St{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ua.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ua.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var dd=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var ri=class extends St{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as pd}from"jose";var ii,md=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ii)try{ii=await pd(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:ii,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var si="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",qa="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ai=class n extends ue{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=gd(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=fd(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Ye(this.policyName,r),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),o&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let C=[],P="";if(Object.entries(y).forEach(([S,N])=>{o&&(P+=`${S} - allowed: ${N} value: ${h.meters[S]??0}
|
|
104
|
+
`),(h.meters[S]??0)>=N&&C.push(S)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",P),C.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${C.join(", ")}'`});t.addResponseSendingFinalHook(async(S,N,A)=>{if(o&&A.log.debug(`QuotaInboundPolicy: backend response - ${S.status}: ${S.statusText}`),!s.quotaOnStatusCodes.includes(S.status))return;let F=re.get(A,si),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};o&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let Z=p.setQuota(d,z,A.requestId);A.waitUntil(Z)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let o=re.get(e,si)??{};Object.assign(o,t),re.set(e,si,o)}static getUsage(e,t){let o=re.get(e,`${qa}-${t}`);if(o===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return o}static#e(e,t,o){re.set(e,`${qa}-${t}`,o)}};function gd(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Be(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}i(gd,"validateAndParseOptions");function fd(n,e){return encodeURIComponent(`${e}-${n}`)}i(fd,"processKey");var Za=ye("zuplo:policies:RateLimitInboundPolicy"),Ha=i(async(n,e,t,o)=>{let r=Q.getLogger(e),s=i((Z,v)=>{let q={};return(!Z||Z==="retry-after")&&(q[xt]=v.toString()),E.tooManyRequests(n,e,void 0,q)},"rateLimited"),u=await Et(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Ye(o,r),C=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${o}/${c}`,P=await se(o,void 0,t),S=new ie(P,e),N=h.getCountAndUpdateExpiry(C,d,e.requestId),A;i(async()=>{let Z=await N;if(Z.count>l){let v=Date.now()+Z.ttlSeconds*1e3;S.put(C,v,Z.ttlSeconds),Za(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${C}' (async mode)`),A=s(p,Z.ttlSeconds)}},"asyncCheck")();let z=await S.get(C);if(z!==void 0&&z>Date.now()){Za(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${C}' (async mode)`);let Z=Math.round((z-Date.now())/1e3);return s(p,Z)}return e.addResponseSendingHook(async Z=>A??Z),n},"AsyncRateLimitInboundPolicyImpl");var $a=ye("zuplo:policies:RateLimitInboundPolicy"),hd="strict",Fa=i(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??hd)==="async")return Ha(n,e,t,o);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[xt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Et(o,t)(n,e,o),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,C=t.headerMode??"retry-after",P=Ye(o,a),N=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${o}/${p}`,A=await P.getCountAndUpdateExpiry(N,y,e.requestId);return A.count>h?($a(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(C,A.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;$a(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ui;function ja(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}i(ja,"headersToNameValuePairs");function yd(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}i(yd,"queryToNameValueParis");function bd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(bd,"parseIntOrUndefined");var za={};async function wd(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return ui||(ui={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?qe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?qe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:ui,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ja(n.headers),queryString:yd(n.query)},response:{status:a.status,statusText:a.statusText,headers:ja(a.headers),content:{size:bd(n.headers.get("content-length"))}}}]}}},d=za[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",C=await H.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});C.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${C.status}: '${await C.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),za[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(wd,"ReadmeMetricsInboundPolicy");var Rd=i(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return r.forEach(u=>{s.delete(u)}),new te(n,{headers:s})},"RemoveHeadersInboundPolicy");var Pd=i(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let s=o?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Id=i(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return r.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Ed=i(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),s=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(s,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ba=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),xd=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Ba():s&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?Ba():n},"RequestSizeLimitInboundPolicy");var At=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),kt=i((n,e,t,o,r)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=zn(t,o,r,c.name),p=ge.instance.schemaValidator[d],h=p(e[c.name]),y=ci(p.errors);h||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),ci=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 Ga(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let C=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=E.badRequest(e,n,{detail:`${C}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",C,[o],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,C=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?C:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=Bn(n.route.path,e.method,r),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,C=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?C:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=ci(l),h=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[o],p),Le(t.validateBody))return h}i(Ga,"handleBodyValidation");function Va(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=At(n),s=kt(r.filter(a=>a.in==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Va,"handleHeadersValidation");function Wa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=At(n),r=kt(o.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(Wa,"handlePathParameterValidation");function Ja(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=At(n),r=kt(o.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(Ja,"handleQueryParameterValidation");var Ka=i(async(n,e,t)=>{g("policy.inbound.request-validation");let o=Ja(e,n,t);if(o!==void 0||(o=Wa(e,n,t),o!==void 0)||(o=Va(e,n,t),o!==void 0))return o;let r=await Ga(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),Td=Ka;var vd=i(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Cd=i(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var Od=i(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(n,{headers:s})},"SetHeadersInboundPolicy");var Sd=i(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let s=o.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Ad=i(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),n)},"SetQueryParamsInboundPolicy");var kd=i(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var Ld=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),_d=i(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await Ld(t.sleepInMs),n},"SleepInboundPolicy");var Nd=i(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,r,o);if(s instanceof Response)return s;if(!(s instanceof te))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${o}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Dd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await se(o,void 0,t),s=new ie(r,e),a=await s.get(o);if(!a){let u=await Md(t,e);s.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Md(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Md,"getAccessToken");var Qa="https://accounts.google.com/o/oauth2/token",li,Ud=i(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),li||(li=await xe.init(t.serviceAccountJson));let r={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(o,void 0,t),a=new ie(s,e),u=await a.get(o);if(!u){let c=await Ne({serviceAccount:li,audience:Qa,payload:r}),l=await Rn(Qa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var qd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Zd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],di,Hd=i(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Zd.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}di||(di=await xe.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=qe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${o}`);let a=await se(o,void 0,t),u=new ie(a,e),c={uid:s,claims:r},l=await st(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:di,audience:qd,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Fs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let o=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await se("zuplo-token",void 0,t),s=await o.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Zn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var Ya="service-account-id-token",pi=class extends ue{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new Fe(this.cacheName):o=new ie(this.cacheName,t);let r=await o.get(Ya);if(!r){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Xt.getIDToken(t,{audience:s}),u=await Hs(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 $s({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");r=l.token,o.put(Ya,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${r}`),e}};var mi,$d=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),mi||(mi=await xe.init(t.serviceAccountJson));let r=await Ne({serviceAccount:mi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var Xa="https://www.googleapis.com/oauth2/v4/token",gi,Fd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),gi||(gi=await xe.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await se(o,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new ie(s,e);let u=await a.get(o);if(!u){let c=await Ne({serviceAccount:gi,audience:Xa,payload:r}),l=await Rn(Xa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var jd=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return n;let{errors:a}=t.validator.default;if(!a)throw new K("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return E.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var eu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=i((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),r=i((P,S)=>i(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(A,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,F,z){return A},"updateTag")},N=o(function(A){return Object.assign({},S,A)},"buildOptions");P.buildOptions=N,P.defaultOptions=S}}),a=r({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+S+"]["+N+"]*",F=new RegExp("^"+A+"$"),z=o(function(v,q){let V=[],j=q.exec(v);for(;j;){let x=[];x.startIndex=q.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=q.exec(v)}return V},"getAllMatches"),Z=o(function(v){let q=F.exec(v);return!(q===null||typeof q>"u")},"isName");P.isExist=function(v){return typeof v<"u"},P.isEmptyObject=function(v){return Object.keys(v).length===0},P.merge=function(v,q,V){if(q){let j=Object.keys(q),x=j.length;for(let I=0;I<x;I++)V==="strict"?v[j[I]]=[q[j[I]]]:v[j[I]]=q[j[I]]}},P.getValue=function(v){return P.isExist(v)?v:""},P.isName=Z,P.getAllMatches=z,P.nameRegexp=A}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var N=class{static{i(this,"XmlNode")}static{o(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,F){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:F})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};S.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var N=a();function A(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,ve="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&Z(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&v(x,I))I+=8;else if(J&&q(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,ve=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:ve+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(A,"readDocType"),o(A,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),o(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),o(z,"isComment");function Z(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="N"&&x[I+4]==="T"&&x[I+5]==="I"&&x[I+6]==="T"&&x[I+7]==="Y"}i(Z,"isEntity"),o(Z,"isEntity");function v(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(v,"isElement"),o(v,"isElement");function q(x,I){return x[I+1]==="!"&&x[I+2]==="A"&&x[I+3]==="T"&&x[I+4]==="T"&&x[I+5]==="L"&&x[I+6]==="I"&&x[I+7]==="S"&&x[I+8]==="T"}i(q,"isAttlist"),o(q,"isAttlist");function V(x,I){return x[I+1]==="!"&&x[I+2]==="N"&&x[I+3]==="O"&&x[I+4]==="T"&&x[I+5]==="A"&&x[I+6]==="T"&&x[I+7]==="I"&&x[I+8]==="O"&&x[I+9]==="N"}i(V,"isNotation"),o(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),o(j,"validateEntityName"),S.exports=A}}),l=r({"../../node_modules/strnum/strnum.js"(P,S){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(v,q={}){if(q=Object.assign({},F,q),!v||typeof v!="string")return v;let V=v.trim();if(q.skipLike!==void 0&&q.skipLike.test(V))return v;if(q.hex&&N.test(V))return Number.parseInt(V,16);{let j=A.exec(V);if(j){let x=j[1],I=j[2],M=Z(j[3]),le=j[4]||j[6];if(!q.leadingZeros&&I.length>0&&x&&V[2]!==".")return v;if(!q.leadingZeros&&I.length>0&&!x&&V[1]!==".")return v;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?q.eNotation?J:v:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:v:I?M===X||x+M===X?J:v:V===X||V===x+X?J:v}}else return v}}i(z,"toNumber"),o(z,"toNumber");function Z(v){return v&&v.indexOf(".")!==-1&&(v=v.replace(/0+$/,""),v==="."?v="0":v[0]==="."?v="0"+v:v[v.length-1]==="."&&(v=v.substr(0,v.length-1))),v}i(Z,"trimZeros"),o(Z,"trimZeros"),S.exports=z}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var N=a(),A=u(),F=c(),z=l(),Z=class{static{i(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=v,this.parseXml=I,this.parseTextData=q,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function v(R){let T=Object.keys(R);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:R[B]}}}i(v,"addExternalEntities"),o(v,"addExternalEntities");function q(R,T,L,B,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!B&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(T,R,L,_,D);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?me(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?me(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(q,"parseTextData"),o(q,"parseTextData");function V(R){if(this.options.removeNSPrefix){let T=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(R=L+T[1])}return R}i(V,"resolveNameSpace"),o(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(R,T,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let B=N.getAllMatches(R,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let $=this.resolveNameSpace(B[ee][1]),U=B[ee][4],de=this.options.attributeNamePrefix+$;if($.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 oe=this.options.attributeValueProcessor($,U,T);oe==null?D[de]=U:typeof oe!=typeof U||oe!==U?D[de]=oe: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 ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),o(x,"buildAttributesMap");var I=o(function(R){R=R.replace(/\r\n?/g,`
|
|
105
|
+
`);let T=new A("!xml"),L=T,B="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let $=b(R,">",D,"Closing Tag is not closed."),U=R.substring(D+2,$).trim();if(this.options.removeNSPrefix){let Oe=U.indexOf(":");Oe!==-1&&(U=U.substr(Oe+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&(B=this.saveTextToParentTag(B,L,_));let de=_.substring(_.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let oe=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=$}else if(R[D+1]==="?"){let $=O(R,D,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new A($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,_,$.tagName)),this.addChild(L,U,_)}D=$.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let $=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=R.substring(D+4,$-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=$}else if(R.substr(D+1,2)==="!D"){let $=F(R,D);this.docTypeEntities=$.entities,D=$.i}else if(R.substr(D+1,2)==="!["){let $=b(R,"]]>",D,"CDATA is not closed.")-2,U=R.substring(D+9,$);B=this.saveTextToParentTag(B,L,_);let de=this.parseTextData(U,L.tagname,_,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):L.add(this.options.textNodeName,de),D=$+2}else{let $=O(R,D,this.options.removeNSPrefix),U=$.tagName,de=$.rawTagName,oe=$.tagExp,Oe=$.attrExpPresent,Ei=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let xi=L;if(xi&&this.options.unpairedTags.indexOf(xi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),U!==T.tagname&&(_+=_?"."+U:U),this.isItStopNode(this.options.stopNodes,_,U)){let Ce="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=$.closeIndex;else{let jn=this.readStopNodeData(R,de,Ei+1);if(!jn)throw new Error(`Unexpected end of ${de}`);D=jn.i,Ce=jn.tagContent}let Fn=new A(U);U!==oe&&Oe&&(Fn[":@"]=this.buildAttributesMap(oe,_,U)),Ce&&(Ce=this.parseTextData(Ce,U,_,!0,Oe,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),Fn.add(this.options.textNodeName,Ce),this.addChild(L,Fn,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),_=_.substr(0,_.length-1),oe=U):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Ce=new A(U);U!==oe&&Oe&&(Ce[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Ce,_),_=_.substr(0,_.lastIndexOf("."))}else{let Ce=new A(U);this.tagsNodeStack.push(L),U!==oe&&Oe&&(Ce[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Ce,_),L=Ce}B="",D=Ei}}else B+=R[D];return T.child},"parseXml");function M(R,T,L){let B=this.options.updateTag(T.tagname,L,T[":@"]);B===!1||(typeof B=="string"&&(T.tagname=B),R.addChild(T))}i(M,"addChild"),o(M,"addChild");var le=o(function(R){if(this.options.processEntities){for(let T in this.docTypeEntities){let L=this.docTypeEntities[T];R=R.replace(L.regx,L.val)}for(let T in this.lastEntities){let L=this.lastEntities[T];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let L=this.htmlEntities[T];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function J(R,T,L,B){return R&&(B===void 0&&(B=Object.keys(T.child).length===0),R=this.parseTextData(R,T.tagname,L,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,B),R!==void 0&&R!==""&&T.add(this.options.textNodeName,R),R=""),R}i(J,"saveTextToParentTag"),o(J,"saveTextToParentTag");function X(R,T,L){let B="*."+L;for(let _ in R){let D=R[_];if(B===D||T===D)return!0}return!1}i(X,"isItStopNode"),o(X,"isItStopNode");function ve(R,T,L=">"){let B,_="";for(let D=T;D<R.length;D++){let ee=R[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===L[0])if(L[1]){if(R[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(ve,"tagExpWithClosingIndex"),o(ve,"tagExpWithClosingIndex");function b(R,T,L,B){let _=R.indexOf(T,L);if(_===-1)throw new Error(B);return _+T.length-1}i(b,"findClosingIndex"),o(b,"findClosingIndex");function O(R,T,L,B=">"){let _=ve(R,T+1,B);if(!_)return;let D=_.data,ee=_.index,$=D.search(/\s/),U=D,de=!0;$!==-1&&(U=D.substring(0,$),D=D.substring($+1).trimStart());let oe=U;if(L){let Oe=U.indexOf(":");Oe!==-1&&(U=U.substr(Oe+1),de=U!==_.data.substr(Oe+1))}return{tagName:U,tagExp:D,closeIndex:ee,attrExpPresent:de,rawTagName:oe}}i(O,"readTagExp"),o(O,"readTagExp");function G(R,T,L){let B=L,_=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let D=b(R,">",L,`${T} is not closed`);if(R.substring(L+2,D).trim()===T&&(_--,_===0))return{tagContent:R.substring(B,L),i:D};L=D}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let D=O(R,L,">");D&&((D&&D.tagName)===T&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(G,"readStopNodeData"),o(G,"readStopNodeData");function me(R,T,L){if(T&&typeof R=="string"){let B=R.trim();return B==="true"?!0:B==="false"?!1:z(R,L)}else return N.isExist(R)?R:""}i(me,"parseValue"),o(me,"parseValue"),S.exports=Z}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function S(Z,v){return N(Z,v)}i(S,"prettify"),o(S,"prettify");function N(Z,v,q){let V,j={};for(let x=0;x<Z.length;x++){let I=Z[x],M=A(I),le="";if(q===void 0?le=M:le=q+"."+M,M===v.textNodeName)V===void 0?V=I[M]:V+=""+I[M];else{if(M===void 0)continue;if(I[M]){let J=N(I[M],v,le),X=z(J,v);I[":@"]?F(J,I[":@"],le,v):Object.keys(J).length===1&&J[v.textNodeName]!==void 0&&!v.alwaysCreateTextNode?J=J[v.textNodeName]:Object.keys(J).length===0&&(v.alwaysCreateTextNode?J[v.textNodeName]="":J=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(J)):v.isArray(M,le,X)?j[M]=[J]:j[M]=J}}}return typeof V=="string"?V.length>0&&(j[v.textNodeName]=V):V!==void 0&&(j[v.textNodeName]=V),j}i(N,"compress"),o(N,"compress");function A(Z){let v=Object.keys(Z);for(let q=0;q<v.length;q++){let V=v[q];if(V!==":@")return V}}i(A,"propName"),o(A,"propName");function F(Z,v,q,V){if(v){let j=Object.keys(v),x=j.length;for(let I=0;I<x;I++){let M=j[I];V.isArray(M,q+"."+M,!0,!0)?Z[M]=[v[M]]:Z[M]=v[M]}}}i(F,"assignAttributes"),o(F,"assignAttributes");function z(Z,v){let{textNodeName:q}=v,V=Object.keys(Z).length;return!!(V===0||V===1&&(Z[q]||typeof Z[q]=="boolean"||Z[q]===0))}i(z,"isLeafTag"),o(z,"isLeafTag"),P.prettify=S}}),h=r({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var S=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,O){O=Object.assign({},N,O);let G=[],me=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let T=0;T<b.length;T++)if(b[T]==="<"&&b[T+1]==="?"){if(T+=2,T=F(b,T),T.err)return T}else if(b[T]==="<"){let L=T;if(T++,b[T]==="!"){T=z(b,T);continue}else{let B=!1;b[T]==="/"&&(B=!0,T++);let _="";for(;T<b.length&&b[T]!==">"&&b[T]!==" "&&b[T]!==" "&&b[T]!==`
|
|
106
106
|
`&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let $;return _.trim().length===0?$="Invalid space after '<'.":$="Tag '"+_+"' is an invalid name.",M("InvalidTag",$,X(b,T))}let D=q(b,T);if(D===!1)return M("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,T));let ee=D.value;if(T=D.index,ee[ee.length-1]==="/"){let $=T-ee.length;ee=ee.substring(0,ee.length-1);let U=j(ee,O);if(U===!0)me=!0;else return M(U.err.code,U.err.msg,X(b,$+U.err.line))}else if(B)if(D.tagClosed){if(ee.trim().length>0)return M("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let $=G.pop();if(_!==$.tagName){let U=X(b,$.tagStartPos);return M("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(R=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let $=j(ee,O);if($!==!0)return M($.err.code,$.err.msg,X(b,T-ee.length+$.err.line));if(R===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let $=I(b,T);if($==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=$}else if(R===!0&&!A(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(A(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function A(b){return b===" "||b===" "||b===`
|
|
107
107
|
`||b==="\r"}i(A,"isWhiteSpace"),o(A,"isWhiteSpace");function F(b,O){let G=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let me=b.substr(G,O-G);if(O>5&&me==="xml")return M("InvalidXml","XML declaration allowed only at the start of the document.",X(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(F,"readPI"),o(F,"readPI");function z(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let G=1;for(O+=8;O<b.length;O++)if(b[O]==="<")G++;else if(b[O]===">"&&(G--,G===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(z,"readCommentAndCDATA"),o(z,"readCommentAndCDATA");var Z='"',v="'";function q(b,O){let G="",me="",R=!1;for(;O<b.length;O++){if(b[O]===Z||b[O]===v)me===""?me=b[O]:me!==b[O]||(me="");else if(b[O]===">"&&me===""){R=!0;break}G+=b[O]}return me!==""?!1:{value:G,index:O,tagClosed:R}}i(q,"readAttributeStr"),o(q,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(b,O){let G=S.getAllMatches(b,V),me={};for(let R=0;R<G.length;R++){if(G[R][1].length===0)return M("InvalidAttr","Attribute '"+G[R][2]+"' has no space in starting.",ve(G[R]));if(G[R][3]!==void 0&&G[R][4]===void 0)return M("InvalidAttr","Attribute '"+G[R][2]+"' is without value.",ve(G[R]));if(G[R][3]===void 0&&!O.allowBooleanAttributes)return M("InvalidAttr","boolean attribute '"+G[R][2]+"' is not allowed.",ve(G[R]));let T=G[R][2];if(!le(T))return M("InvalidAttr","Attribute '"+T+"' is an invalid name.",ve(G[R]));if(!me.hasOwnProperty(T))me[T]=1;else return M("InvalidAttr","Attribute '"+T+"' is repeated.",ve(G[R]))}return!0}i(j,"validateAttributeString"),o(j,"validateAttributeString");function x(b,O){let G=/\d/;for(b[O]==="x"&&(O++,G=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(G))break}return-1}i(x,"validateNumberAmpersand"),o(x,"validateNumberAmpersand");function I(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,x(b,O);let G=0;for(;O<b.length;O++,G++)if(!(b[O].match(/\w/)&&G<20)){if(b[O]===";")break;return-1}return O}i(I,"validateAmpersand"),o(I,"validateAmpersand");function M(b,O,G){return{err:{code:b,msg:O,line:G.line||G,col:G.col}}}i(M,"getErrorObject"),o(M,"getErrorObject");function le(b){return S.isName(b)}i(le,"validateAttrName"),o(le,"validateAttrName");function J(b){return S.isName(b)}i(J,"validateTagName"),o(J,"validateTagName");function X(b,O){let G=b.substring(0,O).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(X,"getLineNumberForPosition"),o(X,"getLineNumberForPosition");function ve(b){return b.startIndex+b[1].length}i(ve,"getPositionFromMatch"),o(ve,"getPositionFromMatch")}}),y=r({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,S){var{buildOptions:N}=s(),A=d(),{prettify:F}=p(),z=h(),Z=class{static{i(this,"XMLParser")}static{o(this,"XMLParser")}constructor(v){this.externalEntities={},this.options=N(v)}parse(v,q){if(typeof v!="string")if(v.toString)v=v.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(q){q===!0&&(q={});let x=z.validate(v,q);if(x!==!0)throw Error(`${x.err.msg}:${x.err.line}:${x.err.col}`)}let V=new A(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(v);return this.options.preserveOrder||j===void 0?j:F(j,this.options)}addEntity(v,q){if(q.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(v.indexOf("&")!==-1||v.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(q==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[v]=q}};S.exports=Z}});let C=y();return new C(n)},"getXmlParser");var fi=class extends Ve{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Be(e.parseOnStatusCodes):void 0,this.parser=eu({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let u=await e.text();r=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(c,u),new k(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var hi=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new K(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var en=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new m("BackgroundDispatcher: options.msDelay is required");this.#e=new Y(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),ht().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var tu=10,nu=3e4,yi=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#o;#r;#i={};constructor(e,t){if(typeof t=="number"){let o=t;this.#n=o*1e3,this.#r=nu,this.#o=tu}else{let o=t;this.#n=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:nu,this.#o=tu}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await zd(()=>this.#u(e)!==void 0||!this.#a,this.#r+this.#o+1,this.#o);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);ht().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(t===void 0)throw new m(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function zd(n,e,t){let o=Date.now();for(;!n();){let r=Date.now()-o;if(r>e)throw new m(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(t)}}i(zd,"waitUntilTrue");var wi,Ri=class extends Se{static{i(this,"AzureBlobPlugin")}constructor(e){super();let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new en(this.#t,{msDelay:o}),this.#e=e,g("azure-blog-csv-plugin")}async initialize(e){e.addRequestHook((t,o)=>(wi=o,o.addResponseSendingFinalHook(async r=>{let s=await this.#e.generateLogEntry(r,t,o);this.#n.enqueue(s)}),t))}#e;#t=i(async e=>{if(e.length===0)return;let t=Bd(e[0]),o=Vd(e,t);await Wd(o,this.#e)},"#dispatch");#n};function Bd(n){return Object.keys(n)}i(Bd,"getHeaders");function Gd(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
|
|
108
108
|
`)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(Gd,"escapeCsvValue");function Vd(n,e){let t=[];t.push(e.join(","));for(let o of n){let r=[];for(let s of e){let a=o[s];r.push(Gd(a))}t.push(r.join(","))}return t.join(`
|
|
109
|
-
`)}i(Vd,"generateCsvContent");async function Wd(n,e){let o=`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${f.instance.instanceId}.csv`,{sasUrl:r}=e,s=`${r.split("?")[0]}/${o}?${r.split("?")[1]}`;try{let a=await H.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(bi({message:a.statusText,status:a.status,details:await a.text()}),bi({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){bi(a)}}i(Wd,"uploadToAzureBlobStorage");function bi(n){if(!wi){let t=ht(),o=ne({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(o);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,wi.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(bi,"logError");async function Jd(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:o,headers:r={}}=e,s=new URL(n,f.instance.zuploEdgeApiUrl),a={method:t,headers:{Authorization:`Bearer ${f.instance.authApiJWT}`,"Content-Type":"application/json",...r}};o&&(a.body=JSON.stringify(o));let u=await H.fetch(s,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(Jd,"apiServices");var Pi=["sha-1","sha-256","sha-384","sha-512"]
|
|
109
|
+
`)}i(Vd,"generateCsvContent");async function Wd(n,e){let o=`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${f.instance.instanceId}.csv`,{sasUrl:r}=e,s=`${r.split("?")[0]}/${o}?${r.split("?")[1]}`;try{let a=await H.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(bi({message:a.statusText,status:a.status,details:await a.text()}),bi({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){bi(a)}}i(Wd,"uploadToAzureBlobStorage");function bi(n){if(!wi){let t=ht(),o=ne({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(o);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,wi.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(bi,"logError");async function Jd(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:o,headers:r={}}=e,s=new URL(n,f.instance.zuploEdgeApiUrl),a={method:t,headers:{Authorization:`Bearer ${f.instance.authApiJWT}`,"Content-Type":"application/json",...r}};o&&(a.body=JSON.stringify(o));let u=await H.fetch(s,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(Jd,"apiServices");var Pi=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{i(this,"BaseCryptoBeta")}};var Ii=class extends $n{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Pi.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Pi.join(", ")}`);let o=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,o);return Array.from(new Uint8Array(r)).map(u=>u.toString(16).padStart(2,"0")).join("")}};export{Rr as AWSLoggingPlugin,fl as AmberfloMeteringInboundPolicy,Ur as AmberfloMeteringPolicy,bl as ApiAuthKeyInboundPolicy,qr as ApiKeyInboundPolicy,Zr as AsertoAuthZInboundPolicy,Or as AuditLogDataStaxProvider,Sr as AuditLogPlugin,El as Auth0JwtInboundPolicy,Nc as AwsLambdaHandlerExtensions,jr as AxiomaticsAuthZInboundPolicy,Ri as AzureBlobPlugin,en as BackgroundDispatcher,yi as BackgroundLoader,xl as BasicAuthInboundPolicy,Fa as BasicRateLimitInboundPolicy,Y as BatchDispatch,Gr as BrownoutInboundPolicy,Dl as CachingInboundPolicy,Ml as ChangeMethodInboundPolicy,Ul as ClearHeadersInboundPolicy,ql as ClearHeadersOutboundPolicy,Zl as ClerkJwtInboundPolicy,Hl as CognitoJwtInboundPolicy,Yr as ComplexRateLimitInboundPolicy,Wl as CompositeInboundPolicy,Jl as CompositeOutboundPolicy,m as ConfigurationError,vo as ContentTypes,re as ContextData,Ii as CryptoBeta,Kl as CurityPhantomTokenInboundPolicy,Yo as DataDogLoggingPlugin,Er as DataDogMetricsPlugin,dr as DynaTraceLoggingPlugin,vr as DynatraceMetricsPlugin,Yl as FirebaseJwtInboundPolicy,Xl as FormDataToJsonInboundPolicy,ed as GeoFilterInboundPolicy,Vo as GoogleCloudLoggingPlugin,nr as Handler,E as HttpProblems,pn as HttpStatusCode,ue as InboundPolicy,td as JWTScopeValidationInboundPolicy,mr as LokiLoggingPlugin,ft as LookupResult,ie as MemoryZoneReadThroughCache,nd as MockApiInboundPolicy,cd as MoesifInboundPolicy,ni as MonetizationInboundPolicy,oi as OktaFGAAuthZInboundPolicy,dd as OktaJwtInboundPolicy,ri as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,Ve as OutboundPolicy,tt as ProblemResponseFormatter,md as PropelAuthJwtInboundPolicy,ai as QuotaInboundPolicy,Fa as RateLimitInboundPolicy,wd as ReadmeMetricsInboundPolicy,Rd as RemoveHeadersInboundPolicy,Pd as RemoveHeadersOutboundPolicy,Id as RemoveQueryParamsInboundPolicy,Ed as ReplaceStringOutboundPolicy,xd as RequestSizeLimitInboundPolicy,Ka as RequestValidationInboundPolicy,vd as RequireOriginInboundPolicy,Ut as ResponseSendingEvent,qt as ResponseSentEvent,k as RuntimeError,rn as SYSTEM_LOGGER,Td as SchemaBasedRequestValidation,Ze as SemanticAttributes,hi as ServiceProviderImpl,Cd as SetBodyInboundPolicy,Od as SetHeadersInboundPolicy,Sd as SetHeadersOutboundPolicy,Ad as SetQueryParamsInboundPolicy,kd as SetStatusOutboundPolicy,_d as SleepInboundPolicy,ga as StripeMonetizationPlugin,Kt as StripeWebhookVerificationInboundPolicy,hr as SumoLogicLoggingPlugin,Nd as SupabaseJwtInboundPolicy,Me as SystemRouteName,Dt as TelemetryPlugin,Dd as UpstreamAzureAdServiceAuthInboundPolicy,Ud as UpstreamFirebaseAdminAuthInboundPolicy,Hd as UpstreamFirebaseUserAuthInboundPolicy,pi as UpstreamGcpFederatedAuthInboundPolicy,$d as UpstreamGcpJwtInboundPolicy,Fd as UpstreamGcpServiceAuthInboundPolicy,br as VMWareLogInsightLoggingPlugin,jd as ValidateJsonSchemaInbound,fi as XmlToJsonOutboundPolicy,Lt as ZoneCache,te as ZuploRequest,Xt as ZuploServices,Jd as apiServices,Dc as awsLambdaHandler,Re as environment,zn as getIdForParameterSchema,su as getIdForRefSchema,Bn as getIdForRequestBodySchema,iu as getRawOperationDataIdentifierName,Oo as httpStatuses,jc as openApiSpecHandler,Bc as redirectHandler,au as sanitizedIdentifierName,Co as serialize,sd as setMoesifContext,g as trackFeature,Wc as urlForwardHandler,Kc as urlRewriteHandler,Qc as webSocketHandler,Yc as webSocketPipelineHandler,Gc as zuploServiceProxy};
|
|
110
110
|
/*! For license information please see index.js.LEGAL.txt */
|