@zuplo/runtime 6.38.0 → 6.38.2

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 CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as f,b as Ue,e as Re,f as lu,g as Gn,h as Vn,i as du,j as pu}from"./chunk-3X22TV3R.js";import{a as i,b as uu,c as cu}from"./chunk-PPV7V43C.js";var Ls=uu(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.parse=ec;wn.serialize=tc;var Wu=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ju=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Ku=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Qu=/^[\u0020-\u003A\u003D-\u007E]*$/,Yu=Object.prototype.toString,Xu=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function ec(n,e){let t=new Xu,o=n.length;if(o<2)return t;let r=e?.decode||nc,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=As(n,s,a),d=ks(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let h=As(n,a+1,c),y=ks(n,c,h),v=r(n.slice(h,y));t[p]=v}s=c+1}while(s<o);return t}i(ec,"parse");function As(n,e,t){do{let o=n.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<t);return t}i(As,"startIndex");function ks(n,e,t){for(;e>t;){let o=n.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return t}i(ks,"endIndex");function tc(n,e,t){let o=t?.encode||encodeURIComponent;if(!Wu.test(n))throw new TypeError(`argument name is invalid: ${n}`);let r=o(e);if(!Ju.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(!Ku.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!Qu.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!oc(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(tc,"serialize");function nc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(nc,"decode");function oc(n){return Yu.call(n)==="[object Date]"}i(oc,"isDate")});var mu=!1;function lt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(lt,"code");function dt(n,e){return mu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(dt,"run");function gu(n){return dt(n,lt([31],39))}i(gu,"red");function fu(n){return dt(n,lt([32],39))}i(fu,"green");function hu(n){return dt(n,lt([33],39))}i(hu,"yellow");function yu(n){return dt(n,lt([34],39))}i(yu,"blue");function bu(n){return dt(n,lt([35],39))}i(bu,"magenta");function wu(n){return dt(n,lt([36],39))}i(wu,"cyan");var ip=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 Si=[gu,fu,hu,yu,bu,wu];function Ru(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(Ru,"hashCode");function Ai(n){let e=Math.abs(Ru(n));return Si[e%Si.length]}i(Ai,"generateColor");function ki(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(ki,"format");function Fe(n,e,t,o){let r={seen:[],stylize:Pu,showHidden:e??!1,depth:t??2,colors:o??!1,customInspect:!0};return r.colors&&(r.stylize=Eu),on(r,n,r.depth)}i(Fe,"inspect");Fe.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]};Fe.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Pu(n,e){return n}i(Pu,"stylizeNoColor");function Iu(n){return typeof n=="boolean"}i(Iu,"isBoolean");function _i(n){return n===void 0}i(_i,"isUndefined");function Eu(n,e){let t=Fe.styles[e];return t?"\x1B["+Fe.colors[t][0]+"m"+n+"\x1B["+Fe.colors[t][1]+"m":n}i(Eu,"stylizeWithColor");function Wn(n){return typeof n=="function"}i(Wn,"isFunction");function Ni(n){return typeof n=="string"}i(Ni,"isString");function xu(n){return typeof n=="number"}i(xu,"isNumber");function Di(n){return n===null}i(Di,"isNull");function Mi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Mi,"hasOwn");function Jn(n){return Xn(n)&&eo(n)==="[object RegExp]"}i(Jn,"isRegExp");function Xn(n){return typeof n=="object"&&n!==null}i(Xn,"isObject");function Kn(n){return Xn(n)&&(eo(n)==="[object Error]"||n instanceof Error)}i(Kn,"isError");function Li(n){return Xn(n)&&eo(n)==="[object Date]"}i(Li,"isDate");function eo(n){return Object.prototype.toString.call(n)}i(eo,"objectToString");function Tu(n){let e={};return n.forEach(function(t,o){e[t]=!0}),e}i(Tu,"arrayToHash");function vu(n,e,t,o,r){let s=[];for(let a=0,u=e.length;a<u;++a)Mi(e,String(a))?s.push(Yn(n,e,t,o,String(a),!0)):s.push("");return r.forEach(function(a){a.match(/^\d+$/)||s.push(Yn(n,e,t,o,a,!0))}),s}i(vu,"formatArray");function Qn(n){return"["+Error.prototype.toString.call(n)+"]"}i(Qn,"formatError");function on(n,e,t){if(n.customInspect&&e&&Wn(e.inspect)&&e.inspect!==Fe&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ni(d)||(d=on(n,d,t)),d}let o=Cu(n,e);if(o)return o;let r=Object.keys(e),s=Tu(r);try{n.showHidden&&Object.getOwnPropertyNames&&(r=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(r.indexOf("message")>=0||r.indexOf("description")>=0))return Qn(e);if(r.length===0){if(Wn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Jn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Li(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Qn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Wn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Jn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Li(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Qn(e)),r.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Jn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=vu(n,e,t,s,r):l=r.map(function(d){return Yn(n,e,t,s,d,u)}),n.seen.pop(),Ou(l,a,c)}i(on,"formatValue");function Yn(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")),Mi(o,r)||(a="["+r+"]"),u||(n.seen.indexOf(c.value)<0?(Di(t)?u=on(n,c.value,null):u=on(n,c.value,t-1),u.indexOf(`
25
+ import{a as h,b as Ue,e as Pe,f as Ru,g as Kn,h as Qn,i as Pu,j as Iu}from"./chunk-3X22TV3R.js";import{a as i,b as bu,c as wu}from"./chunk-PPV7V43C.js";var qs=bu(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.parse=lc;In.serialize=dc;var oc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ic=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,sc=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ac=/^[\u0020-\u003A\u003D-\u007E]*$/,uc=Object.prototype.toString,cc=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function lc(n,e){let t=new cc,r=n.length;if(r<2)return t;let o=e?.decode||pc,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?r:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=Ds(n,s,a),d=Ms(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let f=Ds(n,a+1,c),y=Ms(n,c,f),v=o(n.slice(f,y));t[p]=v}s=c+1}while(s<r);return t}i(lc,"parse");function Ds(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}i(Ds,"startIndex");function Ms(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}i(Ms,"endIndex");function dc(n,e,t){let r=t?.encode||encodeURIComponent;if(!oc.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!ic.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+o;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(!sc.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!ac.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!mc(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(dc,"serialize");function pc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(pc,"decode");function mc(n){return uc.call(n)==="[object Date]"}i(mc,"isDate")});var Eu=!1;function dt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(dt,"code");function pt(n,e){return Eu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(pt,"run");function xu(n){return pt(n,dt([31],39))}i(xu,"red");function Tu(n){return pt(n,dt([32],39))}i(Tu,"green");function vu(n){return pt(n,dt([33],39))}i(vu,"yellow");function Cu(n){return pt(n,dt([34],39))}i(Cu,"blue");function Ou(n){return pt(n,dt([35],39))}i(Ou,"magenta");function Su(n){return pt(n,dt([36],39))}i(Su,"cyan");var Ep=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 Ni=[xu,Tu,vu,Cu,Ou,Su];function Au(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(Au,"hashCode");function Di(n){let e=Math.abs(Au(n));return Ni[e%Ni.length]}i(Di,"generateColor");function Mi(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Mi,"format");function je(n,e,t,r){let o={seen:[],stylize:ku,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=_u),an(o,n,o.depth)}i(je,"inspect");je.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]};je.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ku(n,e){return n}i(ku,"stylizeNoColor");function Lu(n){return typeof n=="boolean"}i(Lu,"isBoolean");function Ui(n){return n===void 0}i(Ui,"isUndefined");function _u(n,e){let t=je.styles[e];return t?"\x1B["+je.colors[t][0]+"m"+n+"\x1B["+je.colors[t][1]+"m":n}i(_u,"stylizeWithColor");function Yn(n){return typeof n=="function"}i(Yn,"isFunction");function Hi(n){return typeof n=="string"}i(Hi,"isString");function Nu(n){return typeof n=="number"}i(Nu,"isNumber");function $i(n){return n===null}i($i,"isNull");function Zi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Zi,"hasOwn");function Xn(n){return rr(n)&&or(n)==="[object RegExp]"}i(Xn,"isRegExp");function rr(n){return typeof n=="object"&&n!==null}i(rr,"isObject");function er(n){return rr(n)&&(or(n)==="[object Error]"||n instanceof Error)}i(er,"isError");function qi(n){return rr(n)&&or(n)==="[object Date]"}i(qi,"isDate");function or(n){return Object.prototype.toString.call(n)}i(or,"objectToString");function Du(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(Du,"arrayToHash");function Mu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Zi(e,String(a))?s.push(nr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(nr(n,e,t,r,a,!0))}),s}i(Mu,"formatArray");function tr(n){return"["+Error.prototype.toString.call(n)+"]"}i(tr,"formatError");function an(n,e,t){if(n.customInspect&&e&&Yn(e.inspect)&&e.inspect!==je&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Hi(d)||(d=an(n,d,t)),d}let r=qu(n,e);if(r)return r;let o=Object.keys(e),s=Du(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(er(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tr(e);if(o.length===0){if(Yn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Xn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(qi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(er(e))return tr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Yn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Xn(e)&&(a=" "+RegExp.prototype.toString.call(e)),qi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),er(e)&&(a=" "+tr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Xn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Mu(n,e,t,s,o):l=o.map(function(d){return nr(n,e,t,s,d,u)}),n.seen.pop(),Uu(l,a,c)}i(an,"formatValue");function nr(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||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")),Zi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?($i(t)?u=an(n,c.value,null):u=an(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")),_i(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(Yn,"formatProperty");function Cu(n,e){if(_i(e))return n.stylize("undefined","undefined");if(Ni(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(xu(e))return n.stylize(""+e,"number");if(Iu(e))return n.stylize(""+e,"boolean");if(Di(e))return n.stylize("null","null")}i(Cu,"formatPrimitive");function Ou(n,e,t){let o=0;return n.reduce(function(s,a){return o++,a.indexOf(`
33
- `)>=0&&o++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
32
+ `))):u=n.stylize("[Circular]","special")),Ui(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),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(nr,"formatProperty");function qu(n,e){if(Ui(e))return n.stylize("undefined","undefined");if(Hi(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Nu(e))return n.stylize(""+e,"number");if(Lu(e))return n.stylize(""+e,"boolean");if($i(e))return n.stylize("null","null")}i(qu,"formatPrimitive");function Uu(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
+ `)>=0&&r++,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(Ou,"reduceToSingleString");var Ui=i((n,...e)=>ki(Fe,n,e),"format");var to=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Ai(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=Ui(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${r}ms`)}`;console.log(s),this.last=Date.now()}},no=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Su(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Su,"extract");var rn;function ye(n){let e=globalThis.DEBUG;rn||(rn=new no(Su(e)));let t=new to(rn,n);return rn.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 et=ye("zuplo:runtime:external-service");function Au(){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(Au,"getServiceAuth");async function qi(n,e){let t=Au();if(t)if(et(`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{et("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await ku(r,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),h=Zi(d.ENVIRONMENT_TYPE),y=await oo(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${h}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw et("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}`);et(`Calling external service: ${c.toString()}`);let l=await sn(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 et("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw et("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(qi,"externalServiceHandler");async function ku(n,e,t,o){let r=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Zi(o);et(`Hashing service name: ${s}-${r}.${s}-${a}-${u}`);let c=await oo(`${s}-${r}`),l=await oo(`${s}-${a}-${u}`);return`${c}.${l}`}i(ku,"hashServiceName");async function oo(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(oo,"hashSegment");function Zi(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Zi,"sanitizeEnvironmentType");var Hi=new Map;Hi.set("service:",qi);var sn=globalThis.fetch;function ro(n,e){let t=Lu(e);if(typeof n=="string"){let o=new URL(n),r=Hi.get(o.protocol);return r?r(n,t):sn(n,t)}else return sn(n,t)}i(ro,"internalFetch");globalThis.fetch=ro;var Lu=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 _u={fetch:ro},Z=_u;Function.prototype.toString=function(){return"[native code]"};var an=globalThis,$i=an.caches;if($i){let n=$i.open;an.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete an.caches.default,Object.freeze(an.caches)}var Fi=new Map,io=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)})}},je=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=Fi.get(e);o||(o=new io(t),Fi.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 so="__zuplo-expiry-header",Nt=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(so);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(so,`${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(so,`${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 je(o),this.#n=new Nt(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 ji="zuplo-request-id",pt="zp-rid",ao="zp-body-removed",tt="cf-ray",zi="x-real-ip",uo="cf-ipcity",co="cf-ipcontinent",lo="cf-ipcountry",po="cf-iplongitude",mo="cf-iplatitude",Bi="cf-region",Gi="cf-region-code",Vi="cf-metro-code",Wi="cf-postal-code",Ji="cf-timezone",Ki="zp-ipcity",Qi="zp-ipcontinent",Yi="zp-ipcountry",Xi="zp-iplongitude",es="zp-iplatitude",ts="true-client-ip",go="zp-asn",fo="zp-asorg",ho="zp-colo",yo="zp-postalcode",bo="zp-metrocode",wo="zp-region",Ro="zp-regioncode",Po="zp-timezone",ns=[uo,co,lo,po,mo,go,fo,ho,yo,bo,wo,Ro,Po],os=["zp-","cf-"],rs=[pt,tt,ao];var Dt=Symbol("zuplo_meters"),Mt=Symbol("zuplo_dynamic_meters"),un="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 xc}from"@opentelemetry/api";import{SpanStatusCode as Nu,trace as Du}from"@opentelemetry/api";import{SpanStatusCode as To,trace as vo}from"@opentelemetry/api";var is=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ss(n){is=n}i(ss,"setTelemetryInitFunction");var as=i(n=>is(n),"proxyHandler");var ze=class{static{i(this,"RuntimePlugin")}},Ie=class extends ze{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},cn=class extends Ie{static{i(this,"MeteringPlugin")}},Ut=class extends ze{static{i(this,"TelemetryPlugin")}};var ln=new Set,us=new Set;function g(n){us.has(n)||(us.add(n),ln.add(n))}i(g,"trackFeature");function cs(){let n=[...ln];return ln.clear(),n}i(cs,"getUnsentFeatures");function ls(n){for(let e of n)ln.add(e)}i(ls,"restoreFeatures");var qt=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})}})}},nt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await qt.problemResponseFormat(e,t,o)}};function dn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&dn(t)}return Object.freeze(n)}i(dn,"deepFreeze");var ne=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 dn(this.#e)}get params(){return dn(this.#t)}user};var Co={},qe=[],Io=[],Eo=[],xo=[];var pn={addPlugin(n){qe.push(n)},addRequestHook(n){Io.push(n)},addResponseSendingHook(n){Eo.push(n)},addResponseSendingFinalHook(n){xo.push(n)}},ps=i(async(n,e)=>{if(Io.length===0)return n;let t=vo.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of Io){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof ne||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:To.ERROR}),l}});if(a instanceof ne)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),ms=i(async(n,e,t)=>{if(Eo.length===0)return n;let o=vo.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of Eo)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:To.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),gs=i(async(n,e,t)=>{if(xo.length===0)return;let o=vo.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of xo)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:To.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),ds=!1;async function fs(n){if(!ds){n&&(g("runtime.extensions"),await n(pn)),Co.value=pn;for(let e of qe)if(e instanceof Ut){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});ss(t)}await Promise.all(qe.map(async e=>{e instanceof Ie&&await e.initialize(pn)})),qt.setProblemResponseFormat(pn.problemResponseFormat),ds=!0}}i(fs,"initializeRuntime");var Oo={Json:"application/json",Form:"application/x-www-form-urlencoded"};function So(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Oo.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Oo.Json)||!e?JSON.stringify(n):n}i(So,"serialize");function mt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(mt,"isSystemRoute");var de=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>Du.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:Nu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async R=>{let A=a.pop();return A?A(r,s,t,u):await this.#e(async F=>{let z=await o(F,s);return Mu(z)},t)(R,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(mt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Zt(r,l);s.dispatchEvent(p);let h=Ee.getContextExtensions(s),y=h.latestRequest,v;try{v=await p.mutableResponse}catch(R){return t.errorHandler(r,s,"Error retrieving mutableResponse",R)}try{v=await h.onResponseSending(v,y,s)}catch(R){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",R)}try{v=await ms(v,y,s)}catch(R){return t.errorHandler(r,s,"Error invoking 'context.onResponseSending' hook",R)}s.dispatchEvent(new Ht(r,v));try{await h.onResponseSendingFinal(l,y,s)}catch(R){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",R),R}try{await gs(l,y,s)}catch(R){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",R),R}return v},"#toZuploPipeline")};function Mu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(So(n),{headers:{"content-type":"application/json"}})}i(Mu,"resultToResponse");var Be=class extends ze{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")};function _e(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${f.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",f.instance.deploymentName??"unknown"),n.set("User-Agent",f.instance.systemUserAgent),n.set("zp-compat-date",f.instance.build.COMPATIBILITY_DATE??"none")}i(_e,"setZuploHeaders");var mn=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(p=>{let h=Object.assign({},p);return delete h.requestContentLength,delete h.responseContentLength,h}),u=cs(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=new Headers({"content-type":"application/json"});_e(l);let d=await Z.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),ls(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send metrics to Ellie.",t)}},"dispatchFunction")};var ue=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 fe=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(tt)??void 0,c=n.headers.get(ts)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=Ee.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 mn(e)),qe.forEach(v=>{if(v instanceof Be){let R=v.getTransport();y.push(R)}}),y.forEach(v=>{v.pushMetrics(h,e)}),a},"metricsProcessor");var Ao=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 de({processors:[fe],handler:t,gateway:e}),r=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var gn=(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))(gn||{}),hs={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 Uu={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"},ko=Uu;function qu(n){return`${new URL(n.url).pathname}`}i(qu,"instance");function Zu(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},o=n.headers.get(tt);return o&&(t.rayId=o),t}i(Zu,"trace");var Hu=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:qu(e),trace:Zu(e,t),...o},additionalHeaders:r,statusText:ko[n.status]}),"merge"),Lo=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?nt.format(e,t,o):nt.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:hs[e],...t}}},E=class extends Lo{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=Hu(this.getProblemFromStatus(e),t,o,r,s);return nt.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:$u}=Object.prototype,{propertyIsEnumerable:Fu}=Object.prototype;function _o(n){return $u.call(n)}i(_o,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function gt(n){return xe(n)&&n!==""}i(gt,"isNonEmptyString");function ys(n){return _o(n)==="[object RegExp]"}i(ys,"isRegexp");function bs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Fu.call(n,e))]}i(bs,"getOwnEnumerableKeys");function ot(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ot,"isObject");function No(n){return typeof n=="number"&&!isNaN(n)}i(No,"isNumber");function Do(n){return n===!0||n===!1}i(Do,"isBoolean");function ws(n){return typeof n>"u"}i(ws,"isUndefined");function Rs(n){return ws(n)||n===null}i(Rs,"isUndefinedOrNull");function $t(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i($t,"isErrorLike");var Ps=new Map;function Ge(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=Ps.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 Ps.set(n,o),o}i(Ge,"statusCodesStringToNumberArray");function Ze(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(Ze,"getValueFromRequestUser");function rt(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(xe(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(rt,"parseValueToStringArray");function Is(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(!ot(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!gt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!No(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&&!Do(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=Mo(t,"allowedHeaders"),r=Mo(t,"allowedMethods"),s=Mo(t,"exposeHeaders"),a;try{a=rt(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(Is,"parseCorsPolicies");function Mo(n,e){let t;if(n[e]!==void 0)try{t=rt(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(Mo,"parseOptionalProperty");var fn=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"),hn=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 Uo=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,v=ju(l,d,p,y,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),E.notFound(a,u))},"optionsHandler"),r=new de({processors:[fe],handler:o,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),ju=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=fn(a.allowedOrigins,t);return u?{isValid:!0,headers:hn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Es=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 de({processors:[fe],handler:t,gateway:e}),r=new ue({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 Ve=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 ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),xs=i((n,e)=>{let t=i(async(r,s)=>{let a=Co.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 Ve)}})}return E.notFound(r,s)},"notFoundHandler"),o=new de({processors:[fe],handler:t,gateway:e});n.addRoute(zu,o.execute)},"registerNotMatchedHandler");var Bu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ts=i(n=>{Bu.forEach(e=>n.delete(e))},"stripCorsHeaders"),yn=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 Ts(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=Gu(r,t.routeData.corsPolicies),u=Vu(n,a),c=new Headers(s.headers);return Ts(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"),Gu=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"),Vu=i((n,e)=>{let t=fn(e.allowedOrigins,n.headers.get("origin"));return t?hn(e,t):{}},"getCorsHeaders");var qo=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 de({processors:[yn],handler:t,gateway:e}),r=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as vs,trace as Cs}from"@opentelemetry/api";var He={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 bn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(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}},ce=class extends bn{static{i(this,"InboundPolicy")}},We=class extends bn{static{i(this,"OutboundPolicy")}};var $o=class extends ce{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)}},Fo=class extends We{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)}},Zo=new Map;function Ft(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!Zo.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 ce)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new $o(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}')`);Zo.set(a.name,c)}),t.map(s=>{let a=Zo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Ft,"getInboundPolicyInstances");var Ho=new Map;function jt(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],o=n.path),t.filter(s=>!Ho.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 We)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Fo(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}'`);Ho.set(a.name,c)}),t.map(s=>{let a=Ho.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(jt,"getOutboundPolicyInstances");var jo=i(n=>async(e,t)=>{let o=Ee.getContextExtensions(t),r=Cs.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 ne||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:vs.ERROR}),d.recordException(h),h}});if(l instanceof ne)u=l;else if(l instanceof Request)u=new ne(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),zo=i(n=>async(e,t,o)=>{let r=Cs.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(He.PolicyName,c.policyName),d.setAttribute(He.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:vs.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),it=i(async(n,e,t,o)=>{let r=Ft(e.route,t.routeData.policies),s=jt(e.route,t.routeData.policies);return Ss({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Os({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>Ss({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Os,"createInternalPolicyProcessor");async function Ss({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=jo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=zo(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(Ss,"executePolicyProcessor");var _s=cu(Ls(),1);function Ns(n,e){try{let t=/v\d+(-\d+)?/g,r=(0,_s.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(Ns,"devPortalBaseURL");var Ds="/__zuplo/dev-portal",rc="dev-portal-id",ic="dev-portal-host",sc="zp-account",ac="zp-project",uc="dev-portal-build",cc=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Uu,"reduceToSingleString");var Fi=i((n,...e)=>Mi(je,n,e),"format");var ir=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Di(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=Fi(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},sr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Hu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Hu,"extract");var un;function be(n){let e=globalThis.DEBUG;un||(un=new sr(Hu(e)));let t=new ir(un,n);return un.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(be,"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 tt=be("zuplo:runtime:external-service");function $u(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i($u,"getServiceAuth");async function ji(n,e){let t=$u();if(t)if(tt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.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[o])u=`https://${t.customServiceMapping[o]}`;else if(h.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{tt("Using sha256 service routing");let d=h.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await Zu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),f=zi(d.ENVIRONMENT_TYPE),y=await ar(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${f}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw tt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);tt(`Calling external service: ${c.toString()}`);let l=await cn(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 tt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw tt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(ji,"externalServiceHandler");async function Zu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=zi(r);tt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ar(`${s}-${o}`),l=await ar(`${s}-${a}-${u}`);return`${c}.${l}`}i(Zu,"hashServiceName");async function ar(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(ar,"hashSegment");function zi(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(zi,"sanitizeEnvironmentType");var Bi=new Map;Bi.set("service:",ji);var cn=globalThis.fetch;function ur(n,e){let t=Fu(e);if(typeof n=="string"){let r=new URL(n),o=Bi.get(r.protocol);return o?o(n,t):cn(n,t)}else return cn(n,t)}i(ur,"internalFetch");globalThis.fetch=ur;var Fu=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 ju={fetch:ur},H=ju;Function.prototype.toString=function(){return"[native code]"};var ln=globalThis,Gi=ln.caches;if(Gi){let n=Gi.open;ln.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete ln.caches.default,Object.freeze(ln.caches)}var Vi=new Map,cr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},ze=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Vi.get(e);r||(r=new cr(t),Vi.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var lr="__zuplo-expiry-header",Nt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(lr);if(!s){try{await t.delete(r)}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(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(lr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(lr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,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 r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new ze(r),this.#n=new Nt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var Wi="zuplo-request-id",mt="zp-rid",dr="zp-body-removed",nt="cf-ray",Ji="x-real-ip",pr="cf-ipcity",mr="cf-ipcontinent",gr="cf-ipcountry",fr="cf-iplongitude",hr="cf-iplatitude",Ki="cf-region",Qi="cf-region-code",Yi="cf-metro-code",Xi="cf-postal-code",es="cf-timezone",ts="zp-ipcity",ns="zp-ipcontinent",rs="zp-ipcountry",os="zp-iplongitude",is="zp-iplatitude",ss="true-client-ip",yr="zp-asn",br="zp-asorg",wr="zp-colo",Rr="zp-postalcode",Pr="zp-metrocode",Ir="zp-region",Er="zp-regioncode",xr="zp-timezone",as=[pr,mr,gr,fr,hr,yr,br,wr,Rr,Pr,Ir,Er,xr],us=["zp-","cf-"],cs=[mt,nt,dr];var Dt=Symbol("zuplo_meters"),Mt=Symbol("zuplo_dynamic_meters"),dn="system-logger";var te=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,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as Nc}from"@opentelemetry/api";import{SpanStatusCode as zu,trace as Bu}from"@opentelemetry/api";import{SpanStatusCode as Or,trace as Sr}from"@opentelemetry/api";var ls=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ds(n){ls=n}i(ds,"setTelemetryInitFunction");var ps=i(n=>ls(n),"proxyHandler");var Be=class{static{i(this,"RuntimePlugin")}},ye=class extends Be{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},pn=class extends ye{static{i(this,"MeteringPlugin")}},qt=class extends Be{static{i(this,"TelemetryPlugin")}};var mn=new Set,ms=new Set;function g(n){ms.has(n)||(ms.add(n),mn.add(n))}i(g,"trackFeature");function gs(){let n=[...mn];return mn.clear(),n}i(gs,"getUnsentFeatures");function fs(n){for(let e of n)mn.add(e)}i(fs,"restoreFeatures");var Ut=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{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,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},rt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Ut.problemResponseFormat(e,t,r)}};function gn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&gn(t)}return Object.freeze(n)}i(gn,"deepFreeze");var re=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return gn(this.#e)}get params(){return gn(this.#t)}user};var Ar={},He=[],Tr=[],vr=[],Cr=[];var fn={addPlugin(n){He.push(n)},addRequestHook(n){Tr.push(n)},addResponseSendingHook(n){vr.push(n)},addResponseSendingFinalHook(n){Cr.push(n)}},ys=i(async(n,e)=>{if(Tr.length===0)return n;let t=Sr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Tr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Or.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),bs=i(async(n,e,t)=>{if(vr.length===0)return n;let r=Sr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of vr)await r.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:Or.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ws=i(async(n,e,t)=>{if(Cr.length===0)return;let r=Sr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Cr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Or.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),hs=!1;async function Rs(n){if(!hs){n&&(g("runtime.extensions"),await n(fn)),Ar.value=fn;for(let e of He)if(e instanceof qt){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});ds(t)}await Promise.all(He.map(async e=>{e instanceof ye&&await e.initialize(fn)})),Ut.setProblemResponseFormat(fn.problemResponseFormat),hs=!0}}i(Rs,"initializeRuntime");var kr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Lr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(kr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(kr.Json)||!e?JSON.stringify(n):n}i(Lr,"serialize");function gt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var de=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>Bu.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){let c=t.errorHandler(r,o,"Error executing request handler.",u);return a.setStatus({code:zu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async R=>{let A=a.pop();return A?A(o,s,t,u):await this.#e(async F=>{let z=await r(F,s);return Gu(z)},t)(R,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ht(o,l);s.dispatchEvent(p);let f=Ee.getContextExtensions(s),y=f.latestRequest,v;try{v=await p.mutableResponse}catch(R){return t.errorHandler(o,s,"Error retrieving mutableResponse",R)}try{v=await f.onResponseSending(v,y,s)}catch(R){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",R)}try{v=await bs(v,y,s)}catch(R){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",R)}s.dispatchEvent(new $t(o,v));try{await f.onResponseSendingFinal(l,y,s)}catch(R){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",R),R}try{await ws(l,y,s)}catch(R){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",R),R}return v},"#toZuploPipeline")};function Gu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Lr(n),{headers:{"content-type":"application/json"}})}i(Gu,"resultToResponse");var Ge=class extends Be{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 r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};function _e(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${h.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",h.instance.deploymentName??"unknown"),n.set("User-Agent",h.instance.systemUserAgent),n.set("zp-compat-date",h.instance.build.COMPATIBILITY_DATE??"none")}i(_e,"setZuploHeaders");var hn=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:r}=h.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=h.instance.build,a=e.map(p=>{let f=Object.assign({},p);return delete f.requestContentLength,delete f.responseContentLength,f}),u=gs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=new Headers({"content-type":"application/json"});_e(l);let d=await H.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),fs(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send metrics to Ellie.",t)}},"dispatchFunction")};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var fe=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(nt)??void 0,c=n.headers.get(ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=Ee.getContextExtensions(e).latestRequest,f={timestamp:o,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:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new hn(e)),He.forEach(v=>{if(v instanceof Ge){let R=v.getTransport();y.push(R)}}),y.forEach(v=>{v.pushMetrics(f,e)}),a},"metricsProcessor");var _r=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=h.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"),r=new de({processors:[fe],handler:t,gateway:e}),o=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var yn=(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))(yn||{}),Ps={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 Vu={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"},Nr=Vu;function Wu(n){return`${new URL(n.url).pathname}`}i(Wu,"instance");function Ju(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=n.headers.get(nt);return r&&(t.rayId=r),t}i(Ju,"trace");var Ku=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Wu(e),trace:Ju(e,t),...r},additionalHeaders:o,statusText:Nr[n.status]}),"merge"),Dr=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?rt.format(e,t,r):rt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ps[e],...t}}},E=class extends Dr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Ku(this.getProblemFromStatus(e),t,r,o,s);return rt.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:Qu}=Object.prototype,{propertyIsEnumerable:Yu}=Object.prototype;function Mr(n){return Qu.call(n)}i(Mr,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function ft(n){return xe(n)&&n!==""}i(ft,"isNonEmptyString");function Is(n){return Mr(n)==="[object RegExp]"}i(Is,"isRegexp");function Es(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Yu.call(n,e))]}i(Es,"getOwnEnumerableKeys");function ot(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ot,"isObject");function qr(n){return typeof n=="number"&&!isNaN(n)}i(qr,"isNumber");function Ur(n){return n===!0||n===!1}i(Ur,"isBoolean");function xs(n){return typeof n>"u"}i(xs,"isUndefined");function Ts(n){return xs(n)||n===null}i(Ts,"isUndefinedOrNull");function Zt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Zt,"isErrorLike");var vs=new Map;function Ve(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="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=vs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return vs.set(n,r),r}i(Ve,"statusCodesStringToNumberArray");function $e(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i($e,"getValueFromRequestUser");function it(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(xe(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(it,"parseValueToStringArray");function Cs(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(!ot(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ft(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!qr(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&&!Ur(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 r=Hr(t,"allowedHeaders"),o=Hr(t,"allowedMethods"),s=Hr(t,"exposeHeaders"),a;try{a=it(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:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Cs,"parseCorsPolicies");function Hr(n,e){let t;if(n[e]!==void 0)try{t=it(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Hr,"parseOptionalProperty");var bn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),wn=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 r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var $r=i((n,e)=>{let t=e.routeData.corsPolicies,r=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 f=n.lookup(c,l);if(!f)return E.notFound(a,u);let y=f.routeConfiguration,v=Xu(l,d,p,y,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),E.notFound(a,u))},"optionsHandler"),o=new de({processors:[fe],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Xu=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.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(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=bn(a.allowedOrigins,t);return u?{isValid:!0,headers:wn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Os=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"),r=new de({processors:[fe],handler:t,gateway:e}),o=new ue({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var We=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 ec=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ss=i((n,e)=>{let t=i(async(o,s)=>{let a=Ar.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof We)}})}return E.notFound(o,s)},"notFoundHandler"),r=new de({processors:[fe],handler:t,gateway:e});n.addRoute(ec,r.execute)},"registerNotMatchedHandler");var tc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],As=i(n=>{tc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Rn=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return As(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(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=nc(o,t.routeData.corsPolicies),u=rc(n,a),c=new Headers(s.headers);return As(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"),nc=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(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),rc=i((n,e)=>{let t=bn(e.allowedOrigins,n.headers.get("origin"));return t?wn(e,t):{}},"getCorsHeaders");var Zr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new de({processors:[Rn],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ks,trace as Ls}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 Pn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(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}},ce=class extends Pn{static{i(this,"InboundPolicy")}},Je=class extends Pn{static{i(this,"OutboundPolicy")}};var zr=class extends ce{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Br=class extends Je{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Fr=new Map;function Ft(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Fr.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}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (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 '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ce)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new zr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Fr.set(a.name,c)}),t.map(s=>{let a=Fr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Ft,"getInboundPolicyInstances");var jr=new Map;function jt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!jr.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 '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (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 '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Je)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Br(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);jr.set(a.name,c)}),t.map(s=>{let a=jr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(jt,"getOutboundPolicyInstances");var Gr=i(n=>async(e,t)=>{let r=Ee.getContextExtensions(t),o=Ls.getTracer("pipeline");return await o.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 o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof re||p instanceof Response)return d.end(),p;{let f=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:ks.ERROR}),d.recordException(f),f}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Vr=i(n=>async(e,t,r)=>{let o=Ls.getTracer("pipeline");return await o.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 o.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,r);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:ks.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),st=i(async(n,e,t,r)=>{let o=Ft(e.route,t.routeData.policies),s=jt(e.route,t.routeData.policies);return Ns({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function _s({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ns({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(_s,"createInternalPolicyProcessor");async function Ns({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Gr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Vr(r),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return o.errorHandler(n,e,"Error executing policies",u)}}i(Ns,"executePolicyProcessor");var Us=wu(qs(),1);function Hs(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Us.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Hs,"devPortalBaseURL");var $s="/__zuplo/dev-portal",gc="dev-portal-id",fc="dev-portal-host",hc="zp-account",yc="zp-project",bc="dev-portal-build",wc=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -55,20 +55,20 @@ import{a as f,b as Ue,e as Re,f as lu,g as Gn,h as Vn,i as du,j as pu}from"./chu
55
55
  </div>
56
56
  </body>
57
57
  </html>
58
- `,Ms=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=f.instance.deploymentName,r=f.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(f.instance.isLocalDevelopment)return new Response(cc,{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=Ns(r,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:v,body:R}=c;return f.instance.build.ACCOUNT_NAME&&y.set(sc,f.instance.build.ACCOUNT_NAME),f.instance.build.PROJECT_NAME&&y.set(ac,f.instance.build.PROJECT_NAME),y.set(rc,o),y.set(ic,d.host),y.set(uc,f.instance.build.BUILD_ID),await Z.fetch(h.toString(),{headers:y,method:v,body:R,redirect:"manual"})},"devPortalRoute"),a=new de({processors:[fe,it],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Us=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Ds.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),r=new de({processors:[fe],handler:o,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ds}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,r.execute)},"registerDevPortalLegacyRedirectRoute");var qs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,{deploymentName:o,zudokuHostUrl:r}=f.instance,s=i(async(c,l)=>{if(f.instance.isLocalDevelopment){let v=new URL("local-dev.html",r);return Z.fetch(v)}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 Z.fetch(h.toString(),{headers:c.headers,method:c.method,body:c.body,redirect:"manual"});if([301,302,307,308].includes(y.status)){let v=new Response(null,y),R=y.headers.get("location");return R&&(R=R.replace(`/deployments/${o}`,""),v.headers.set("location",R)),v}if(f.instance.isWorkingCopy&&y.status===404&&d.pathname===t){let v=new URL("loading.html",r);return Z.fetch(v)}return y},"devPortalRoute"),a=new de({processors:[fe,it],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_ZUDOKU_ROUTE",methods:["GET","HEAD"],path:`${t}(.*)`,systemRouteName:"zudoku-portal"});n.addRoute(u,a.execute)},"registerZudokuRoute"),Zs=i((n,e)=>{let{deploymentName:t,zudokuHostUrl:o}=f.instance,r=i(async u=>{let c=new URL(`deployments/${t}/__zuplo/docs`,o),l=await Z.fetch(c.toString(),{headers:u.headers,method:u.method,body:u.body,redirect:"manual"});if(l.status===404){let d={status:"empty"};return new Response(JSON.stringify(d,null,2),{headers:{"content-type":"application/json","cache-control":"no-cache"}})}return l},"buildRoute"),s=new de({processors:[fe,it],handler:r,gateway:e}),a=new ue({label:"SYSTEM_API_DOCS_ZUDOKU_BUILD_ROUTE",methods:["GET","HEAD"],path:"/__zuplo/docs",systemRouteName:"zudoku-portal"});n.addRoute(a,s.execute)},"registerZudokuStatusRoute");var Bo=0,zt=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){Bo>=Number.MAX_SAFE_INTEGER&&(Bo=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:Bo++};this.#t[e](u,a)}};var he=class extends ze{static{i(this,"LogPlugin")}};var Rn=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 Bt=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 lc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),dc=new Map(lc);var pc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Go=Symbol(".toJSON was called"),mc=i(n=>{n[Go]=!0;let e=n.toJSON();return delete n[Go],e},"toJSON"),gc=i(n=>dc.get(n)??Error,"getErrorConstructor"),Hs=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&&$t(n)){let l=gc(n.name);t=new l}else t={};if(e.push(n),s>=r)return t;if(a&&typeof n.toJSON=="function"&&n[Go]!==!0)return mc(n);let c=i(l=>Hs({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 pc)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:$t(n[l])?c(n[l]):n[l],enumerable:o?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function st(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,o=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Hs({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:o,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(st,"serializeError");var fc=/file:\/\/\/(.*?)\/dist\//g,hc="at async Event.respondWith";function Vo(n){return typeof n!="string"?n:n.split(`
59
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let o=e.replaceAll(fc,"").replaceAll(hc,"").trim();return t===0||o.length===0?o:` ${o}`}).filter(e=>e.length>0).join(`
60
- `)}i(Vo,"cleanStack");function Pn(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:`
58
+ `,Zs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=h.instance.deploymentName,o=h.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(wc,{headers:{"content-type":"text/html"}});if(!r)return E.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Hs(o,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:v,body:R}=c;return h.instance.build.ACCOUNT_NAME&&y.set(hc,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&y.set(yc,h.instance.build.PROJECT_NAME),y.set(gc,r),y.set(fc,d.host),y.set(bc,h.instance.build.BUILD_ID),await H.fetch(f.toString(),{headers:y,method:v,body:R,redirect:"manual"})},"devPortalRoute"),a=new de({processors:[fe,st],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Fs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring($s.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new de({processors:[fe],handler:r,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${$s}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var js=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,{deploymentName:r,zudokuHostUrl:o}=h.instance,s=i(async(c,l)=>{if(h.instance.isLocalDevelopment){let v=new URL("local-dev.html",o);return H.fetch(v)}if(!r)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 f=new URL(`deployments/${r}${p}`,o),y=await H.fetch(f.toString(),{headers:c.headers,method:c.method,body:c.body,redirect:"manual"});if([301,302,307,308].includes(y.status)){let v=new Response(null,y),R=y.headers.get("location");return R&&(R=R.replace(`/deployments/${r}`,""),v.headers.set("location",R)),v}if(h.instance.isWorkingCopy&&y.status===404&&d.pathname===t){let v=new URL("loading.html",o);return H.fetch(v)}return y},"devPortalRoute"),a=new de({processors:[fe,st],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_ZUDOKU_ROUTE",methods:["GET","HEAD"],path:`${t}(.*)`,systemRouteName:"zudoku-portal"});n.addRoute(u,a.execute)},"registerZudokuRoute"),zs=i((n,e)=>{let{deploymentName:t,zudokuHostUrl:r}=h.instance,o=i(async u=>{let c=new URL(`deployments/${t}/__zuplo/docs`,r),l=await H.fetch(c.toString(),{headers:u.headers,method:u.method,body:u.body,redirect:"manual"});if(l.status===404){let d={status:"empty"};return new Response(JSON.stringify(d,null,2),{headers:{"content-type":"application/json","cache-control":"no-cache"}})}return l},"buildRoute"),s=new de({processors:[fe,st],handler:o,gateway:e}),a=new ue({label:"SYSTEM_API_DOCS_ZUDOKU_BUILD_ROUTE",methods:["GET","HEAD"],path:"/__zuplo/docs",systemRouteName:"zudoku-portal"});n.addRoute(a,s.execute)},"registerZudokuStatusRoute");var Wr=0,zt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Wr>=Number.MAX_SAFE_INTEGER&&(Wr=0);let u={logId:crypto.randomUUID(),requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Wr++};this.#t[e](u,a)}};var he=class extends Be{static{i(this,"LogPlugin")}};var En=class{static{i(this,"LoggingContext")}constructor(e,t,r,o){this.#e=e,this.custom=t,this.originalRequest=r,this.route=o}#e;custom;originalRequest;route;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Bt=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var Rc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Pc=new Map(Rc);var Ic=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Jr=Symbol(".toJSON was called"),Ec=i(n=>{n[Jr]=!0;let e=n.toJSON();return delete n[Jr],e},"toJSON"),xc=i(n=>Pc.get(n)??Error,"getErrorConstructor"),Bs=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Zt(n)){let l=xc(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Jr]!==!0)return Ec(n);let c=i(l=>Bs({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,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 Ic)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Zt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function at(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Bs({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(at,"serializeError");var Tc=/file:\/\/\/(.*?)\/dist\//g,vc="at async Event.respondWith";function Kr(n){return typeof n!="string"?n:n.split(`
59
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Tc,"").replaceAll(vc,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
60
+ `)}i(Kr,"cleanStack");function xn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
61
61
  `,newlineOrSpace:`
62
- `,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 v=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return v.length<=u.inlineCharacterLimit?v:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
- `).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"||ys(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((v,R)=>{let A=a.length-1===R?p.newline:","+p.newlineOrSpace,N=s(v,u,c+d,l+1);return u.transform&&(N=u.transform(a,R,N)),p.indent+N+A}).join("")+p.pad+"]";return o.pop(),h(y)}if(ot(a)){let y=bs(a);if(u.filter&&(y=y.filter(R=>u.filter?.(a,R))),y.length===0)return"{}";o.push(a);let v="{"+p.newline+y.map((R,A)=>{let N=y.length-1===A?p.newline:","+p.newlineOrSpace,S=typeof R=="symbol",F=!S&&/^[a-z$_][$\w]*$/i.test(R),z=S||F?R:s(R,u,"",l+1),H=s(a[R],u,c+d,l+1);return u.transform&&(H=u.transform(a,R,H)),p.indent+String(z)+": "+H+N}).join("")+p.pad+"}";return o.pop(),h(v)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
64
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Pn,"stringifyObject");function $e(n){return Fs(st(n))}i($e,"serializeMessage");function Ne(n){return n.map(e=>$e(e))}i(Ne,"serializeMessages");function ft(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:Fs(st(e))}i(ft,"extractBestMessage");function $s(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if($t(t))if(t.stack)e.push(t.stack);else{let o=Pn(st(t));e.push(o)}else if(typeof t=="object"){let o=Pn(t);e.push(o)}else{let o=Wo(t);e.push(o)}}),e.join(`
65
- `)}i($s,"messagesToMultilineText");function Fs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Fs,"stringifyNonString");function Wo(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"?_o(n):"unknown"}i(Wo,"stringifyNonStringToText");import{importPKCS8 as yc,SignJWT as bc}from"jose";async function be(n,e,t){for(let o=0;o<=n.retries;o++){let r=Z.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 De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new bc(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function js(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Jo("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(js,"exchangeIDTokenForGcpWorkloadToken");async function zs({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return Gs(`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(zs,"generateServiceAccountIDToken");async function Bs(n,e,t){return Jo(n,{token:e,returnSecureToken:!0},t)}i(Bs,"exchangeFirebaseJwtForIdToken");async function In(n,e,t){return Jo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(In,"exchangeGgpJwtForIdToken");async function Jo(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Gs(n,o,t)}i(Jo,"fetchTokenFromBody");async function Gs(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(Gs,"fetchToken");var Te=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 yc(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 wc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Vs=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:wc[e.level],body:Ne(e.messages),attributes:t}},"unifiedFormatter");async function te(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 Ws(f.instance,[o])}catch(o){console.error(o)}}i(te,"sendRemoteGlobalLog");async function Ws(n,e){let t=Vs(n);try{let o=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});_e(o),await Z.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Ws,"sendLogs");var Rc=i(n=>async e=>{e.length!==0&&await Ws(n,e)},"dispatchFunction"),En,Gt=class{static{i(this,"UnifiedLogTransport")}constructor(e){En||(En=new Y("unified-log-transport",1,Rc(e)))}log(e,t){En.enqueue(e),t.waitUntil(En.waitUntilFlushed())}};var Ko=class extends he{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Vt(this.options)}},Pc="https://logging.googleapis.com/v2/entries:write?alt=json",Qo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Vt=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 Te.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:Ne(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Qo[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=ft(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 Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await Z.fetch(Pc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});o.ok||await te({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`]},o)}catch{await te({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 xn="gcp";function Tn(n){let e={allMessages:Ne(n.messages)},t="zuplo-production",o=ft(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,severity:Qo[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(Tn,"gcpLogFormat");var Wt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===xn){if(e.messages.length===0)return;this.#e[e.level](Tn(e))}else{let o={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ne(e.messages)};this.#e[e.level](JSON.stringify(o))}}};var tr=class extends he{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Jt(this.options)}},Yo="__ddtags",Xo="__ddattr",er=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ic=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(er(o)):t.push(`${er(o)}:${er(r.toString())}`)}),t.join(",")},"formatTags"),Jt=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[Yo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Yo]!==void 0);a>-1&&(Object.assign(o,s[a][Yo]),s.splice(a,1));let u={},c=t.custom[Xo];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Xo]!==void 0);l>-1&&(Object.assign(u,s[l][Xo]),s.splice(l,1));let d=Ne(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ft(d),service:e.loggingId,ddtags:Ic(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 Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await te({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await te({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 Kt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===xn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Tn(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 nr=ye("zuplo:logging"),vn=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;nr("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(un);return s?r.push(new Kt(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Wt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Gt(e)),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new zt(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){nr("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(un);if(a&&a.captureUserLogs===!0?o.push(new Kt(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Wt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Gt(e)),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Vt({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 Jt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return qe.forEach(u=>{u instanceof he&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new zt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s,a){nr("Gateway.createRequestLoggers");let u=new Rn(o,r,s,a),c=new Bt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Bt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var ht=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Cn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var or=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},On=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Ve||e instanceof ue))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 or(o,e,t);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new Cn(`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 ht(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 ht(r.config,r.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as Ec}from"node:async_hooks";var Sn={context:new Ec};var rr;function Js(n){rr=n}i(Js,"setGlobalZuploEventContext");function Je(){if(rr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return rr}i(Je,"getGlobalZuploEventContext");function Ks({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);os.includes(r.toLowerCase())&&!rs.includes(o.toLowerCase())&&t.delete(o)}t.delete(zi)}else ns.forEach(o=>{t.delete(o)});return t}i(Ks,"normalizeIncomingRequestHeaders");var Ke=ye("zuplo:runtime"),ge=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;Ke("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(Ke("Gateway.initialize"),!n.#e){let s=await vn.init(o),a=await e(),u={...a,corsPolicies:Is(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(){Ke("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=[it,yn,fe];setupRoutes=i(()=>{Ke("Gateway.setupRoutes");let e=this.routeData,t=new On;if(e.routes.length===0)return Ao(t,this),qo(t,this),Uo(t,this),Es(t,this),t;let{enabled:o,version:r}=this.runtimeSettings.developerPortal;o&&(r==="zudoku"?(qs(t,this),Zs(t,this)):r==="legacy"&&(Us(t,this),Ms(t,this))),Ao(t,this),qo(t,this),Uo(t,this);for(let s of qe)s instanceof Ie&&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 de({processors:this.#o,handler:a,gateway:this}),c=new Ve(s);t.addRoute(c,u.execute)}),xs(t,this),t},"setupRoutes");errorHandler(e,t,o,r){Ke("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=st(r.cause);"stack"in a&&(a.stack=Vo(a.stack)),s={cause:a}}else{let a=st(r);"stack"in a&&(a.stack=Vo(a.stack)),s={cause:a}}return E.internalServerError(e,t,{detail:r.message,...s})}async handleRequest(e,t){let o=e.headers.get(pt)??e.headers.get(ji)??crypto.randomUUID(),r=e.headers.get(tt);Js(t);let s=Ks({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(pt,o);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(ao,"true"),a=new Request(a,{headers:S,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 An(e.headers),v=new ne(a,{params:l.params}),R=new kn({logger:p,route:l.routeConfiguration,requestId:o,event:t,custom:d,incomingRequestProperties:y}),A=Sn.context.getStore();A&&(A.context=R);let N=l.routeConfiguration.raw();xc.getActiveSpan()?.setAttributes({"http.route":R.route.path??R.route.pathPattern,"cloud.region":R.incomingRequestProperties.colo,[He.RoutePathPattern]:R.route.pathPattern,[He.RouteOperationId]:N.operationId,[He.RouteTrace]:N["x-zuplo-trace"],[He.RouteSystem]:mt(u)?!0:void 0}),Ee.initialize(R,v);try{if(Q.addLogger(R,h),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(u):!u.pathname.startsWith("/__zuplo")){let H=await ps(v,R);if(H instanceof Response)return H;{let C=Ee.getContextExtensions(R);v=H,C.latestRequest=v}}mt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let S=l.executableHandler;Tc(S,l,a),Ke("Gateway.handleRequest - call user handler");let F=await S(v,R);if(Ke("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(pt)===null&&!F.webSocket){let H=new Headers(F.headers);H.set(pt,o),z=new Response(F.body,{status:F.status,statusText:F.statusText,headers:H,cf:F.cf})}else z=F;return z}catch(S){return S instanceof k?(p.error(S),h.warn(S)):h.error(S),await this.errorHandler(v,R,"Error executing handler",S)}}};function Tc(n,e,t){if(Ke("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(Tc,"checkHandler");var Qs=i(async(n,e,t)=>{let o=ge.instance.routeData.policies,r=Ft([n],o);if(r.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy"),Ys=i(async(n,e,t,o)=>{let r=ge.instance.routeData.policies,s=jt([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 An=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(go);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(fo)??void 0}get city(){return this.#e.get(uo)??this.#e.get(Ki)??void 0}get continent(){return this.#e.get(co)??this.#e.get(Qi)??void 0}get country(){return this.#e.get(lo)??this.#e.get(Yi)??void 0}get latitude(){return this.#e.get(mo)??this.#e.get(es)??void 0}get longitude(){return this.#e.get(po)??this.#e.get(Xi)??void 0}get colo(){return this.#e.get(ho)??void 0}get postalCode(){return this.#e.get(Wi)??this.#e.get(yo)??void 0}get metroCode(){return this.#e.get(Vi)??this.#e.get(bo)??void 0}get region(){return this.#e.get(Bi)??this.#e.get(wo)??void 0}get regionCode(){return this.#e.get(Gi)??this.#e.get(Ro)??void 0}get timezone(){return this.#e.get(Ji)??this.#e.get(Po)??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}}},Zt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ee=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")},kn=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)=>Qs(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Ys(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ee.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 vc="Error initializing gateway. Check your configuration for errors or contact support.",Cc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",ir=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 fs(this.runtimeInit)}catch(s){this.handleError(s,Cc,e)}return as(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,vc,s)}let c={context:void 0};return Sn.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 Oc(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(Oc,"lexer");function ar(n,e){e===void 0&&(e={});for(var t=Oc(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"),v=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"),R=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||v(I)?"[^".concat(sr(a),"]+?"):"(?:(?!".concat(sr(I),")[^").concat(sr(a),"])+?")},"safePattern");l<t.length;){var A=p("CHAR"),N=p("NAME"),S=p("PATTERN");if(N||S){var F=A||"";r.indexOf(F)===-1&&(d+=F,F=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:F,suffix:"",pattern:S||R(F),modifier:p("MODIFIER")||""});continue}var z=A||p("ESCAPED_CHAR");if(z){d+=z;continue}d&&(u.push(d),d="");var H=p("OPEN");if(H){var F=y(),C=p("NAME")||"",q=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:C||(q?c++:""),pattern:C&&!q?R(F):q,prefix:F,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(ar,"parse");function Xs(n,e){return Sc(ar(n,e),e)}i(Xs,"compile");function Sc(n,e){e===void 0&&(e={});var t=Ac(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==="*",v=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!v)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 R=0;R<h.length;R++){var A=r(h[R],p);if(a&&!u[d].test(A))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(A,'"'));l+=p.prefix+A+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var A=r(String(h),p);if(a&&!u[d].test(A))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(A,'"'));l+=p.prefix+A+p.suffix;continue}if(!y){var N=v?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(Sc,"tokensToFunction");function sr(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(sr,"escapeString");function Ac(n){return n&&n.sensitive?"":"i"}i(Ac,"flags");var kc=ye("zuplo:runtime"),cr=new TextEncoder,ea={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"},Lc=["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 lr(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){kc("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=Z.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")}},lr=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:v,singleEncode:R}){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 A,N;(!c||!l)&&([A,N]=_c(this.url,this.headers)),this.service=c||A||"",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 S=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"),S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(z=>v||!Lc.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(`
66
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.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,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=na(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(H=>na(encodeURIComponent(H)))).sort(([z,H],[C,q])=>z<C?-1:z>C?1:H<q?-1:H>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 Qt("AWS4"+this.secretAccessKey,e),s=await Qt(r,this.region),a=await Qt(s,this.service);o=await Qt(a,"aws4_request"),this.cache.set(t,o)}return ur(await Qt(o,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ur(await ta(await this.canonicalString()))].join(`
62
+ `,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 f=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let v=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return v.length<=u.inlineCharacterLimit?v:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Is(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((v,R)=>{let A=a.length-1===R?p.newline:","+p.newlineOrSpace,N=s(v,u,c+d,l+1);return u.transform&&(N=u.transform(a,R,N)),p.indent+N+A}).join("")+p.pad+"]";return r.pop(),f(y)}if(ot(a)){let y=Es(a);if(u.filter&&(y=y.filter(R=>u.filter?.(a,R))),y.length===0)return"{}";r.push(a);let v="{"+p.newline+y.map((R,A)=>{let N=y.length-1===A?p.newline:","+p.newlineOrSpace,S=typeof R=="symbol",F=!S&&/^[a-z$_][$\w]*$/i.test(R),z=S||F?R:s(R,u,"",l+1),$=s(a[R],u,c+d,l+1);return u.transform&&($=u.transform(a,R,$)),p.indent+String(z)+": "+$+N}).join("")+p.pad+"}";return r.pop(),f(v)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
64
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(xn,"stringifyObject");function Fe(n){return Vs(at(n))}i(Fe,"serializeMessage");function Ne(n){return n.map(e=>Fe(e))}i(Ne,"serializeMessages");function ht(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:Vs(at(e))}i(ht,"extractBestMessage");function Gs(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 r=xn(at(t));e.push(r)}else if(typeof t=="object"){let r=xn(t);e.push(r)}else{let r=Qr(t);e.push(r)}}),e.join(`
65
+ `)}i(Gs,"messagesToMultilineText");function Vs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Vs,"stringifyNonString");function Qr(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"?Mr(n):"unknown"}i(Qr,"stringifyNonStringToText");import{importPKCS8 as Cc,SignJWT as Oc}from"jose";async function we(n,e,t){for(let r=0;r<=n.retries;r++){let o=H.fetch(e,t);if(r===n.retries)return o;let s=await o;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,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(we,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Oc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function Ws(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Yr("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(Ws,"exchangeIDTokenForGcpWorkloadToken");async function Js({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Qs(`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(o)},r)}i(Js,"generateServiceAccountIDToken");async function Ks(n,e,t){return Yr(n,{token:e,returnSecureToken:!0},t)}i(Ks,"exchangeFirebaseJwtForIdToken");async function Tn(n,e,t){return Yr(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Tn,"exchangeGgpJwtForIdToken");async function Yr(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Qs(n,r,t)}i(Yr,"fetchTokenFromBody");async function Qs(n,e,t){let r=await we(t,n,e);if(r.status!==200){let s;try{let a=await r.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 r.json()}i(Qs,"fetchToken");var Te=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),r=await Cc(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}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 Sc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ys=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:Sc[e.level],body:Ne(e.messages),attributes:t}},"unifiedFormatter");async function ne(n,e){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,vectorClock:0};await Xs(h.instance,[r])}catch(r){console.error(r)}}i(ne,"sendRemoteGlobalLog");async function Xs(n,e){let t=Ys(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});_e(r),await H.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(Xs,"sendLogs");var Ac=i(n=>async e=>{e.length!==0&&await Xs(n,e)},"dispatchFunction"),vn,Gt=class{static{i(this,"UnifiedLogTransport")}constructor(e){vn||(vn=new Y("unified-log-transport",1,Ac(e)))}log(e,t){vn.enqueue(e),t.waitUntil(vn.waitUntilFlushed())}};var Xr=class extends he{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Vt(this.options)}},kc="https://logging.googleapis.com/v2/entries:write?alt=json",eo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Vt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.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 r={allMessages:Ne(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:eo[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ht(r.allMessages);s.jsonPayload={...r,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 Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await H.fetch(kc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await ne({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}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 Cn="gcp";function On(n){let e={allMessages:Ne(n.messages)},t="zuplo-production",r=ht(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:eo[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&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(On,"gcpLogFormat");var Wt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Cn){if(e.messages.length===0)return;this.#e[e.level](On(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ne(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var oo=class extends he{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Jt(this.options)}},to="__ddtags",no="__ddattr",ro=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Lc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(ro(r)):t.push(`${ro(r)}:${ro(o.toString())}`)}),t.join(",")},"formatTags"),Jt=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.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[to];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[to]!==void 0);a>-1&&(Object.assign(r,s[a][to]),s.splice(a,1));let u={},c=t.custom[no];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[no]!==void 0);l>-1&&(Object.assign(u,s[l][no]),s.splice(l,1));let d=Ne(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ht(d),service:e.loggingId,ddtags:Lc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(f,u),this.batcher.enqueue(f),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 Kt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Cn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[On(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 io=be("zuplo:logging"),Sn=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(h.instance,e),r=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;io("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(dn);return s?o.push(new Kt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Wt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Gt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new zt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){io("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(dn);if(a&&a.captureUserLogs===!0?r.push(new Kt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Wt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Gt(e)),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new Vt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Jt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof he&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new zt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){io("Gateway.createRequestLoggers");let u=new En(r,o,s,a),c=new Bt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Bt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var yt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},An=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var so=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r,this.urlPattern=new URLPattern({pathname:this.fullPath})}urlPattern;fullPath;config;executableHandler},kn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof We||e instanceof ue))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new so(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new An(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new m(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new yt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new yt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as _c}from"node:async_hooks";var Ln={context:new _c};var ao;function ea(n){ao=n}i(ea,"setGlobalZuploEventContext");function Ke(){if(ao===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return ao}i(Ke,"getGlobalZuploEventContext");function ta({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);us.includes(o.toLowerCase())&&!cs.includes(r.toLowerCase())&&t.delete(r)}t.delete(Ji)}else as.forEach(r=>{t.delete(r)});return t}i(ta,"normalizeIncomingRequestHeaders");var Qe=be("zuplo:runtime"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Qe("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Qe("Gateway.initialize"),!n.#e){let s=await Sn.init(r),a=await e(),u={...a,corsPolicies:Cs(a.corsPolicies)},c=new n(u,t,s,o);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(){Qe("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;#r=[st,Rn,fe];setupRoutes=i(()=>{Qe("Gateway.setupRoutes");let e=this.routeData,t=new kn;if(e.routes.length===0)return _r(t,this),Zr(t,this),$r(t,this),Os(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&(o==="zudoku"?(js(t,this),zs(t,this)):o==="legacy"&&(Fs(t,this),Zs(t,this))),_r(t,this),Zr(t,this),$r(t,this);for(let s of He)s instanceof ye&&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 de({processors:this.#r,handler:a,gateway:this}),c=new We(s);t.addRoute(c,u.execute)}),Ss(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Qe("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=at(o.cause);"stack"in a&&(a.stack=Kr(a.stack)),s={cause:a}}else{let a=at(o);"stack"in a&&(a.stack=Kr(a.stack)),s={cause:a}}return E.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t){let r=e.headers.get(mt)??e.headers.get(Wi)??crypto.randomUUID(),o=e.headers.get(nt);ea(t);let s=ta({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(mt,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(dr,"true"),a=new Request(a,{headers:S,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:f}=this.#t.createRequestLoggers(r,o,t,d,a,l.routeConfiguration),y=new _n(e.headers),v=new re(a,{params:l.params}),R=new Nn({logger:p,route:l.routeConfiguration,requestId:r,event:t,custom:d,incomingRequestProperties:y}),A=Ln.context.getStore();A&&(A.context=R);let N=l.routeConfiguration.raw();Nc.getActiveSpan()?.setAttributes({"http.route":R.route.path??R.route.pathPattern,"cloud.region":R.incomingRequestProperties.colo,[Ze.RoutePathPattern]:R.route.pathPattern,[Ze.RouteOperationId]:N.operationId,[Ze.RouteTrace]:N["x-zuplo-trace"],[Ze.RouteSystem]:gt(u)?!0:void 0}),Ee.initialize(R,v);try{if(Q.addLogger(R,f),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(u):!u.pathname.startsWith("/__zuplo")){let $=await ys(v,R);if($ instanceof Response)return $;{let C=Ee.getContextExtensions(R);v=$,C.latestRequest=v}}gt(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let S=l.executableHandler;Dc(S,l,a),Qe("Gateway.handleRequest - call user handler");let F=await S(v,R);if(Qe("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(mt)===null&&!F.webSocket){let $=new Headers(F.headers);$.set(mt,r),z=new Response(F.body,{status:F.status,statusText:F.statusText,headers:$,cf:F.cf})}else z=F;return z}catch(S){return S instanceof k?(p.error(S),f.warn(S)):f.error(S),await this.errorHandler(v,R,"Error executing handler",S)}}};function Dc(n,e,t){if(Qe("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(Dc,"checkHandler");var na=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ft([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),ra=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=jt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var _n=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(yr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(br)??void 0}get city(){return this.#e.get(pr)??this.#e.get(ts)??void 0}get continent(){return this.#e.get(mr)??this.#e.get(ns)??void 0}get country(){return this.#e.get(gr)??this.#e.get(rs)??void 0}get latitude(){return this.#e.get(hr)??this.#e.get(is)??void 0}get longitude(){return this.#e.get(fr)??this.#e.get(os)??void 0}get colo(){return this.#e.get(wr)??void 0}get postalCode(){return this.#e.get(Xi)??this.#e.get(Rr)??void 0}get metroCode(){return this.#e.get(Yi)??this.#e.get(Pr)??void 0}get region(){return this.#e.get(Ki)??this.#e.get(Ir)??void 0}get regionCode(){return this.#e.get(Qi)??this.#e.get(Er)??void 0}get timezone(){return this.#e.get(es)??this.#e.get(xr)??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}}},Ht=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},$t=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ee=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}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,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Nn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>na(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>ra(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ee.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=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,o,r)}};var Mc="Error initializing gateway. Check your configuration for errors or contact support.",qc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",uo=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await Rs(this.runtimeInit)}catch(s){this.handleError(s,qc,e)}return ps(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,Mc,s)}let c={context:void 0};return Ln.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Uc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",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){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){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(Uc,"lexer");function lo(n,e){e===void 0&&(e={});for(var t=Uc(n),r=e.prefixes,o=r===void 0?"./":r,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"),f=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"),v=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"),R=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||v(I)?"[^".concat(co(a),"]+?"):"(?:(?!".concat(co(I),")[^").concat(co(a),"])+?")},"safePattern");l<t.length;){var A=p("CHAR"),N=p("NAME"),S=p("PATTERN");if(N||S){var F=A||"";o.indexOf(F)===-1&&(d+=F,F=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:F,suffix:"",pattern:S||R(F),modifier:p("MODIFIER")||""});continue}var z=A||p("ESCAPED_CHAR");if(z){d+=z;continue}d&&(u.push(d),d="");var $=p("OPEN");if($){var F=y(),C=p("NAME")||"",U=p("PATTERN")||"",V=y();f("CLOSE"),u.push({name:C||(U?c++:""),pattern:C&&!U?R(F):U,prefix:F,suffix:V,modifier:p("MODIFIER")||""});continue}f("END")}return u}i(lo,"parse");function oa(n,e){return Hc(lo(n,e),e)}i(oa,"compile");function Hc(n,e){e===void 0&&(e={});var t=$c(e),r=e.encode,o=r===void 0?function(c){return c}:r,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 f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",v=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!v)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<f.length;R++){var A=o(f[R],p);if(a&&!u[d].test(A))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(A,'"'));l+=p.prefix+A+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var A=o(String(f),p);if(a&&!u[d].test(A))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(A,'"'));l+=p.prefix+A+p.suffix;continue}if(!y){var N=v?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(Hc,"tokensToFunction");function co(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(co,"escapeString");function $c(n){return n&&n.sensitive?"":"i"}i($c,"flags");var Zc=be("zuplo:runtime"),mo=new TextEncoder,ia={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"},Fc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],bt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,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=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new go(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){Zc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=H.fetch(o,s);if(r===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,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},go=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:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:v,singleEncode:R}){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||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let A,N;(!c||!l)&&([A,N]=jc(this.url,this.headers)),this.service=c||A||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let S=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"),S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(z=>v||!Fc.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(`
66
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.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,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=aa(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($=>aa(encodeURIComponent($)))).sort(([z,$],[C,U])=>z<C?-1:z>C?1:$<U?-1:$>U?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(),r=this.cache.get(t);if(!r){let o=await Qt("AWS4"+this.secretAccessKey,e),s=await Qt(o,this.region),a=await Qt(s,this.service);r=await Qt(a,"aws4_request"),this.cache.set(t,r)}return po(await Qt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,po(await sa(await this.canonicalString()))].join(`
67
67
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
68
68
  `,this.signedHeaders,await this.hexBodyHash()].join(`
69
- `)}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=ur(await ta(this.body||""))}return e}};async function Qt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?cr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,cr.encode(e))}i(Qt,"hmac");async function ta(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?cr.encode(n):n)}i(ta,"hash");function ur(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(ur,"buf2hex");function na(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(na,"encodeRfc3986");function _c(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 ea?[ea[s],a]:[s,a]}i(_c,"guessServiceRegion");function Nc(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(Nc,"b64ToUint6");function oa(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|=Nc(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(oa,"base64Decode");function Ln(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Ln,"uint6ToB64");function ra(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(Ln(r>>>18&63),Ln(r>>>12&63),Ln(r>>>6&63),Ln(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ra,"base64Encode");function bt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(bt,"numberToString");function Dc(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(Dc,"getCLFOffset");function dr(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=Dc(n);return`${t}/${o}/${r}:${s}:${a}:${u} ${c}`}i(dr,"toCLFDate");var ia=ye("zuplo:runtime"),Mc="X-Amzn-Trace-Id",Uc="x-amzn-errortype",sa=[],qc=i(async(n,e,t)=>{let o=t;for await(let r of sa)o=await r(n,e,t);return o},"onSendingAwsLambdaEvent"),ve=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Mc)??void 0,this.errorType=t.get(Uc)??void 0}},Zc={addSendingAwsLambdaEventHook:i(n=>{sa.push(n)},"addSendingAwsLambdaEventHook")};async function Hc(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(ia(`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,v;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?v=jc(n,e):v=await Fc(n,e,{useAwsResourcePathStyle:u}),ia("Calling onSendingAwsLambdaEvent hook");let R=await qc(n,e,v);R.body=p,R.isBase64Encoded=h;let A=await l.fetch(d,{body:JSON.stringify(R)});try{return $c(A)}catch(N){if(N instanceof ve){let S=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,S)}throw N}}i(Hc,"awsLambdaHandler");async function $c(n){let e;try{e=await n.json()}catch{throw new ve("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 ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(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 ve(`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 ve(`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 ve(`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 ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);o=oa(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 ve(`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($c,"getResponse");async function Fc(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:dr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Gc(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Fc,"buildEventVersion1");function jc(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:dr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(jc,"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&&Bc(e,r)){let s=await n.arrayBuffer();t=ra(new Uint8Array(s)),o=!0}else t=await n.clone().text();return[t,o]}i(zc,"getBodyResult");function Bc(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(o=>o==="*/*"?!0:o.toLowerCase()===t)>-1}i(Bc,"matchesContentType");function Gc(n,e=!1){if(!e)return n;let t=ar(n),o=Xs(n),r={};return t.forEach(s=>{typeof s=="string"?r[s]=`{${s}}`:r[s.name]=`{${s.name}}`}),o(r)}i(Gc,"getResourcePath");var Vc=[502,503,504];async function wt(n,e){if(Vc.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 pr;function Qe(n){if(pr===void 0){let t=f.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),pr=t}return n.log[pr]}i(Qe,"getHandlerUserLogFunction");async function Wc(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=Jc(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 Z.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(Wc,"openApiSpecHandler");var Jc=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 Kc(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(Kc,"redirectHandler");async function Qc(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}`),Z.fetch(e,{method:n.method,headers:t,body:n.body})}i(Qc,"zuploServiceProxy");function Yc(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(Yc,"join");async function Xc(n,e){g("handler.url-forward");let t=Qe(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=Yc(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(Xc,"urlForwardHandler");var el=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 tl(n,e){g("handler.url-rewrite");let t=Qe(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?el(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(tl,"urlRewriteHandler");async function nl(n,e){g("handler.websocket");let t=e.route.handler.options,o=Qe(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(nl,"webSocketHandler");var mr=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"),aa=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 ua(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 aa(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(ua,"wireUpListeners");async function ol(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,o=Qe(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 A=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${A}'`;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 v=t.policies&&t.policies.inbound?mr(t.policies.inbound,"inbound"):[],R=t.policies&&t.policies.outbound?mr(t.policies.outbound,"outbound"):[];return ua(p,y,n,e,v),ua(y,p,n,e,R),new Response(null,{status:101,webSocket:d})}i(ol,"webSocketPipelineHandler");var gr=class extends he{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new fr(this.options)}},fr=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:$e(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 Z.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 te({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await te({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 hr=class extends he{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new br(this.options)}},yr=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 rl(n,e){return btoa(`${n}:${e}`)}i(rl,"createBasicDigest");var br=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#o=rl(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 yr(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:$e(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 Z.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#o}`}});o.ok||await te({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await te({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 wr=class extends he{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=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:$e(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(`
70
- `),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 Z.fetch(this.#e,{method:"POST",body:t,headers:o});r.ok||await te({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`]},r)}catch{await te({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 il="d3a5b78f823648f5b1df4fe269d41172",Pr=class extends he{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=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??il}`)}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=$s(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=Wo(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 Z.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await te({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await te({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 Er=class extends he{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=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 te({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await te({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:$e(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 Tr=new WeakMap,sl={tags:[]},vr=class extends Be{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Cr(this.options)}static setContext(t,o){let r=Tr.get(t);r||(r=sl);let s=Object.assign({...r},o);Tr.set(t,s)}},Cr=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(Tr.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 Z.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});o.ok||await te({level:"error",messages:["Failed to send metrics to DataDog."]},o)}catch{await te({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Or=new WeakMap,al={dimensions:[]},Sr=class extends Be{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Ar(this.options)}static setContext(t,o){let r=Or.get(t);r||(r=al);let s=Object.assign({...r},o);Or.set(t,s)}},Ar=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(Or.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(`
71
- `),o=await Z.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});o.ok||await te({level:"error",messages:["Failed to send metrics to Dynatrace."]},o)}catch{await te({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var kr=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 Z.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var Lr=class extends Ie{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new _r(e,this.#e,this.#t)}},ca=i(n=>{let e={};return n.forEach((t,o)=>{e[o]=t}),e},"serializableHeaders"),ul={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},_r=class{static{i(this,"AuditPluginImpl")}constructor(e,t,o){this.#t=t;let r={...ul};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?ca(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?ca(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 Nr=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}},Me=class extends Nr{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,o={}){super(o),this.header=e,this.payload=t}};var cl="v1",ll=300;async function la(n,e,t,o=ll,r){return await pl(n,e,t,o,r),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(la,"constructEventAsync");function dl(n,e){return`${e.timestamp}.${n}`}i(dl,"makeHMACContent");async function pl(n,e,t,o,r){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=ml(n,e,cl),l=/\s/.test(t),d=await yl(dl(a,u),t);return gl(a,s,u,d,o,c,l,r)}i(pl,"verifyHeaderAsync");function ml(n,e,t){if(!n)throw new Me(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 Me(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?r.decode(e):e,u=fl(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:o}}i(ml,"parseEventDetails");function gl(n,e,t,o,r,s,a,u){let c=!!t.signatures.filter(h=>hl(h,o)).length,l=`
69
+ `)}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=po(await sa(this.body||""))}return e}};async function Qt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,mo.encode(e))}i(Qt,"hmac");async function sa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?mo.encode(n):n)}i(sa,"hash");function po(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(po,"buf2hex");function aa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(aa,"encodeRfc3986");function jc(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).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=r==="/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 ia?[ia[s],a]:[s,a]}i(jc,"guessServiceRegion");function zc(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(zc,"b64ToUint6");function ua(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=zc(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ua,"base64Decode");function Dn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Dn,"uint6ToB64");function ca(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(Dn(o>>>18&63),Dn(o>>>12&63),Dn(o>>>6&63),Dn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ca,"base64Encode");function wt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(wt,"numberToString");function Bc(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=wt(Math.floor(t/60)),s=wt(t%60);return`${r}${o}${s}`}i(Bc,"getCLFOffset");function fo(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=wt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=wt(n.getHours()),a=wt(n.getMinutes()),u=wt(n.getSeconds()),c=Bc(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(fo,"toCLFDate");var la=be("zuplo:runtime"),Gc="X-Amzn-Trace-Id",Vc="x-amzn-errortype",da=[],Wc=i(async(n,e,t)=>{let r=t;for await(let o of da)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ve=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Gc)??void 0,this.errorType=t.get(Vc)??void 0}},Jc={addSendingAwsLambdaEventHook:i(n=>{da.push(n)},"addSendingAwsLambdaEventHook")};async function Kc(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,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(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)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 bt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(la(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await el(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,v;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?v=Xc(n,e):v=await Yc(n,e,{useAwsResourcePathStyle:u}),la("Calling onSendingAwsLambdaEvent hook");let R=await Wc(n,e,v);R.body=p,R.isBase64Encoded=f;let A=await l.fetch(d,{body:JSON.stringify(R)});try{return Qc(A)}catch(N){if(N instanceof ve){let S=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,S)}throw N}}i(Kc,"awsLambdaHandler");async function Qc(n){let e;try{e=await n.json()}catch{throw new ve("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 ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(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 ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`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 ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);r=ua(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Qc,"getResponse");async function Yc(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[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:r,multiValueHeaders:o,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:fo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:nl(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Yc,"buildEventVersion1");function Xc(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.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:r.hostname,domainPrefix:null,http:{method:n.method,path:r.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:fo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Xc,"buildEventVersion2");async function el(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&tl(e,o)){let s=await n.arrayBuffer();t=ca(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(el,"getBodyResult");function tl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(tl,"matchesContentType");function nl(n,e=!1){if(!e)return n;let t=lo(n),r=oa(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(nl,"getResourcePath");var rl=[502,503,504];async function Rt(n,e){if(rl.includes(n.status)){let t=Q.getLogger(e),o=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:o,headers:s})}}i(Rt,"logBadGatewayResponses");var ho;function Ye(n){if(ho===void 0){let t=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),ho=t}return n.log[ho]}i(Ye,"getHandlerUserLogFunction");async function ol(n,e){g("handler.open-api");let t=h.instance.build.BUILD_ID,{buildAssetsUrl:r}=h.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=il(s);if(!a.isValid)throw new m(a.error);let u;h.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${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 Rt(l,e),l}i(ol,"openApiSpecHandler");var il=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 sl(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(sl,"redirectHandler");async function al(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,h.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${h.instance.authApiJWT}`),H.fetch(e,{method:n.method,headers:t,body:n.body})}i(al,"zuploServiceProxy");function ul(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(ul,"join");async function cl(n,e){g("handler.url-forward");let t=Ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__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=r.__rewriteFunction(n,s),c=ul(u,a.pathname),l=o?`${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}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),Rt(p,e),p}i(cl,"urlForwardHandler");var ll=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function dl(n,e){g("handler.url-rewrite");let t=Ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__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=r.__rewriteFunction(n,a),c=o?ll(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`),Rt(d,e),d}i(dl,"urlRewriteHandler");async function pl(n,e){g("handler.websocket");let t=e.route.handler.options,r=Ye(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="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();r(`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 r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(pl,"webSocketHandler");var yo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),pa=i(async(n,e,t,r,o,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,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function ma(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await pa(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(ma,"wireUpListeners");async function ml(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=Ye(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="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();r(`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 A=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${A}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let y=c.webSocket;y.accept(),p.accept();let v=t.policies&&t.policies.inbound?yo(t.policies.inbound,"inbound"):[],R=t.policies&&t.policies.outbound?yo(t.policies.outbound,"outbound"):[];return ma(p,y,n,e,v),ma(y,p,n,e,R),new Response(null,{status:101,webSocket:d})}i(ml,"webSocketPipelineHandler");var bo=class extends he{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new wo(this.options)}},wo=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Fe(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),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 Ro=class extends he{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Io(this.options)}},Po=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,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 gl(n,e){return btoa(`${n}:${e}`)}i(gl,"createBasicDigest");var Io=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=gl(e.username,e.password),this.#i=h.instance.loggingEnvironmentType,this.#s=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Po(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Fe(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await H.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await ne({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}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 Eo=class extends he{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new xo(this.options)}},xo=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Fe(r),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
70
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await H.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await ne({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}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 fl="d3a5b78f823648f5b1df4fe269d41172",To=class extends he{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new vo(this.options)}},vo=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??fl}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Gs(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=Qr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#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 Co=class extends he{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Oo(this.options)}},Oo=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 r=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}});r.ok||await ne({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}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:r,secretAccessKey:o,region:s}){g("logging.aws"),this.awsClient=new bt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Fe(r),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(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var So=new WeakMap,hl={tags:[]},Ao=class extends Ge{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ko(this.options)}static setContext(t,r){let o=So.get(t);o||(o=hl);let s=Object.assign({...o},r);So.set(t,s)}},ko=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#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.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Y("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(So.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await H.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await ne({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await ne({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Lo=new WeakMap,yl={dimensions:[]},_o=class extends Ge{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new No(this.options)}static setContext(t,r){let o=Lo.get(t);o||(o=yl);let s=Object.assign({...o},r);Lo.set(t,s)}},No=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=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.#r===void 0&&(this.#r=new Y("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Lo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=e.join(`
71
+ `),r=await H.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await ne({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await ne({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Do=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 Mo=class extends ye{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new qo(e,this.#e,this.#t)}},ga=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),bl={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},qo=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...bl};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new Y("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?ga(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?ga(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var Uo=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}},Me=class extends Uo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var wl="v1",Rl=300;async function fa(n,e,t,r=Rl,o){return await Il(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(fa,"constructEventAsync");function Pl(n,e){return`${e.timestamp}.${n}`}i(Pl,"makeHMACContent");async function Il(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=El(n,e,wl),l=/\s/.test(t),d=await Cl(Pl(a,u),t);return xl(a,s,u,d,r,c,l,o)}i(Il,"verifyHeaderAsync");function El(n,e,t){if(!n)throw new Me(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.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 Me(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Tl(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(El,"parseEventDetails");function xl(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(f=>vl(f,r)).length,l=`
72
72
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
73
73
 
74
74
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Me(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -77,11 +77,11 @@ Signature verification is impossible without access to the original signed mater
77
77
  `+d}):new Me(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
78
78
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
79
79
  `+l+`
80
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(gl,"validateComputedSignature");function fl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}i(fl,"parseHeader");function hl(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}i(hl,"secureCompare");async function yl(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),s=new Uint8Array(r),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Dr[s[u]];return a.join("")}i(yl,"computeHMACSignatureAsync");var Dr=new Array(256);for(let n=0;n<Dr.length;n++)Dr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await la(r,o,this.options.signingSecret)}catch(r){let s=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function da(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(da,"isStripeWebhookEvent");var bl={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,r),new k(s)}return r},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,r),new k(s)}return r},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,r),new k(s)}return r},"getUpcomingInvoice")},_n=bl;var Mr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",pa="My API Key";async function ma({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,Mr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:s,email:r}]},p=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ma,"createConsumer");async function ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,Mr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new k(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(ga,"createConsumerInvite");async function fa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=f.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,Mr);r.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(fa,"deleteConsumer");async function ha({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!gt(p))throw new K("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(ha,"createSubscription");async function Rt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}i(Rt,"updateSubscription");async function Pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:s}=f.instance;if(!gt(r))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Pt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Ye="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Nn(n){return n.replaceAll("_","-")}i(Nn,"stripeStatusToMeteringStatus");function at(n){return new Date(n*1e3).toISOString()}i(at,"unixTimestampToISOString");async function Ur(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ma({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await _n.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ga({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Nn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:at(t.data.object.trial_end),trialStartDate:at(t.data.object.trial_start)}),await ha({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await fa({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Ye})}i(Ur,"onCustomerSubscriptionCreated");async function qr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId});await Rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Pe})}return E.ok(n,e,{title:Ye})}i(qr,"onCustomerSubscriptionDeleted");async function Zr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=Nn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=at(t.data.object.trial_end)),await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await _n.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Pt({context:e,stripeSubscriptionId:r,stripeCustomerId:s,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?at(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?at(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Pe})}return E.ok(n,e,{title:Ye})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Pe})}i(Zr,"onCustomerSubscriptionUpdated");var ya=class extends cn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!wl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!da(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Ur(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Zr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qr(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe})}},"stripeWebhookHandler"),s=Os({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:r,gateway:o}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function wl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(wl,"isMetricsRegion");var wa=new WeakMap,ba={},Hr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){wa.set(e,t)}};async function Rl(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=Ge(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(r.includes(s.status)){let a=wa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=ba[t.apiKey];if(!h){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await Z.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${A.message}`),A}}),ba[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Rl,"AmberfloMeteringInboundPolicy");async function ut(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}i(ut,"sha256");var Ra=new Map;async function se(n,e,t){let o,r=`${n}-${e}`,s=Ra.get(r);return s!==void 0?o=s:(o=`zuplo-policy-${await ut(JSON.stringify({policyName:n,options:t}))}`,Ra.set(n,o)),o}i(se,"getPolicyCacheName");var Pa="key-metadata-cache-type";function Pl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Pl,"getKeyValue");async function $r(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let s=i(N=>r.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Pl(a,r);if(!u||u==="")return s("No key present");let c=await Il(u),l=await se(o,void 0,r),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Pa&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(h)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:Pa,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,r.cacheTtlSeconds),n}i($r,"ApiKeyInboundPolicy");async function Il(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Il,"hashValue");var El=$r;var Ia=Symbol("aserto-authz-resource-context"),Fr=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){re.set(e,Ia,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let o=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let r=re.get(t,Ia),s;r?.policyInstance?s=r.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Ze(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:r?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:r?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:r?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await Z.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?o(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),o("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as Tl,jwtVerify as xa}from"jose";import{createLocalJWKSet as xl}from"jose";var jr=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof zr&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=xl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new Br("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new It("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new It("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ea(n,e,t){let o=new jr(n,e,t);return async(r,s)=>o.getKey(r,s)}i(Ea,"createRemoteJWKSet");var It=class extends k{static{i(this,"JWKSError")}},zr=class extends It{static{i(this,"JWKSNoMatchingKey")}},Br=class extends It{static{i(this,"JWKSTimeout")}};var Dn={},vl=i((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Dn[o.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(s=o.useExperimentalInMemoryCache),s){let a=await se(n,void 0,o),u=new ie(a,e);Dn[o.jwkUrl]=Ea(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else Dn[o.jwkUrl]=Tl(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await xa(t,Dn[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),Cl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:o}=await xa(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=i(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=t.authHeader??"Authorization",s=n.headers.get(r),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?vl(o,e):Cl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",h=d[p];return h?(n.user={sub:h,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ol=i(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var Mn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Gr=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Mn(e)}async handler(e,t){let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var Sl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!o)return await s("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await s("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===h&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Un(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Un,"extractDateElements");function Ta(n,e){return new Date(n,e+1,0).getDate()}i(Ta,"getDaysInMonth");function Vr(n,e){return n<=e?e-n:6-n+e+1}i(Vr,"getDaysBetweenWeekdays");var qn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:o,minute:r,second:s};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let s=Ta(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>s?e==="next"?void 0:s:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Vr(d,p):Vr(p,d);l=e==="next"?r+h:r-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Un(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Un(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let s=0;s<e;s++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:s,month:a,weekday:u}=Un(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Al={min:0,max:59},kl={min:0,max:59},Ll={min:0,max:23},_l={min:1,max:31},Nl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Dl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Ml={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ct(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{ct(d,e).forEach(h=>t.add(h))}),t;let r=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(r(n)),t;let a=s[1]==="*"?e.min:r(s[3]),u=s[1]==="*"?e.max:r(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ct,"parseElement");function Wr(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Ml[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new qn({seconds:ct(t,Al),minutes:ct(o,kl),hours:ct(r,Ll),days:ct(s,_l),months:new Set(Array.from(ct(a,Nl)).map(c=>c-1)),weekdays:new Set(Array.from(ct(u,Dl)).map(c=>c%7))})}i(Wr,"parseCronExpression");var Jr=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Wr(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Wr(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(s=>s.matchDate(o))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Ul=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ql(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ql,"digestMessage");var Zl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await ql(JSON.stringify(o)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Hl(n,e,t,o){g("policy.inbound.caching");let r=await se(o,t.cacheId,t),s=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Zl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ul.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}i(Hl,"CachingInboundPolicy");var $l=i(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new ne(n,{method:t.method})},"ChangeMethodInboundPolicy");var Fl=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new ne(n,{headers:r})},"ClearHeadersInboundPolicy");var jl=i(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],s=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var zl=i(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(r);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Bl=i(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Zn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Kr=class extends Zn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Qr=class extends Zn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Gl(n,e){if(Rs(n))throw new Kr(e)}i(Gl,"throwIfUndefinedOrNull");function va(n,e){if(Gl(n,e),!xe(n))throw new Qr(e,"string")}i(va,"throwIfNotString");var Yr=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),s=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Vl=500,Xr=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:o,requestId:r}){va(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Vl);let a,u=new Headers({"content-type":"application/json"});_e(u,r);try{a=await Z.fetch(`${this.clientUrl}${e}`,{method:o,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await ut(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await ut(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},Et;function Xe(n,e){if(Et)return Et;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Et=new Yr,Et;let{redisURL:t,authApiJWT:o}=f.instance;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Et=new Xr(t),Et}i(Xe,"getRateLimitClient");var Wl=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function xt(n,e){return{function:Yl(e,"RateLimitInboundPolicy",n),user:Kl,ip:Jl,all:Ql}[e.rateLimitBy??"ip"]}i(xt,"getRateLimitByFunctions");var Jl=i(async n=>({key:`ip-${Wl(n)}`}),"getIP"),Kl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ql=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Yl(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await o(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(Yl,"wrapUserFunction");var Tt="Retry-After";var Ca=ye("zuplo:policies:ComplexRateLimitInboundPolicy"),ei=Symbol("complex-rate-limit-counters"),ti=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=re.get(e,ei)??{};Object.assign(o,t),re.set(e,ei,t)}static getIncrements(e){return re.get(e,ei)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),s=Xe(this.policyName,r),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});r.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Tt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await xt(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:h,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){r.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:h,limit:N})),v=await s.multiCount(y,t.requestId);return Xl(v,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;Ca(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Xl(n,e){let t=[];for(let o of n){let r=e.find(s=>s.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}i(Xl,"findOverLimits");var ed=i(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=ge.instance,s=Ft(t.policies,r?.routeData.policies);return jo(s)(n,e)},"CompositeInboundPolicy");var td=i(async(n,e,t,o,r)=>{if(g("policy.outbound.composite"),!o.policies||o.policies.length===0)throw new m(`CompositeOutboundPolicy '${r}' must have valid policies defined`);let s=ge.instance,a=jt(o.policies,s?.routeData.policies);return zo(a)(n,e,t)},"CompositeOutboundPolicy");var nd=i(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return E.unauthorized(n,e,{detail:"No authorization header"});let s=od(r);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(o,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function od(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(od,"getToken");var rd=i(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var id=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![r,o].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ne(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var vt="__unknown__",sd=i(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Ot(t.allow?.countries,"allow.countries",o),regionCodes:Ot(t.allow?.regionCodes,"allow.regionCode",o),asns:Ot(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Ot(t.block?.countries,"block.countries",o),regionCodes:Ot(t.block?.regionCodes,"block.regionCode",o),asns:Ot(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??vt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??vt,u=e.incomingRequestProperties.asn?.toString()??vt,c=r.ignoreUnknown&&s===vt,l=r.ignoreUnknown&&a===vt,d=r.ignoreUnknown&&u===vt,p=r.allow.countries,h=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ct(n,e,o,s,a,u);let v=r.block.countries,R=r.block.regionCodes,A=r.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ct(n,e,o,s,a,u):n},"GeoFilterInboundPolicy");function Ct(n,e,t,o,r,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:s}})}i(Ct,"blockedResponse");function Ot(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Ot,"toLowerStringArray");var ad=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(o,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var ud=i(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return ni(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(r),a=[];if(s.length===0)return ni(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Oa(a[u])}else return a.length>0?Oa(a[0]):ni(o,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Oa(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Oa,"generateResponse");var ni=i((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return E.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var cd="Incoming",ld={logRequestBody:!0,logResponseBody:!0};function Sa(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}i(Sa,"headersToObject");function Aa(){return new Date().toISOString()}i(Aa,"timestamp");var oi=new WeakMap,dd={};function pd(n,e){let t=oi.get(n);t||(t=dd);let o=Object.assign({...t},e);oi.set(n,o)}i(pd,"setMoesifContext");async function ka(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}i(ka,"readBody");var md={},ri;function La(){if(!ri)throw new k("Invalid State - no _lastLogger");return ri}i(La,"getLastLogger");function gd(n){let e=md[n];return e||(e=new Y("moesif-inbound",100,async t=>{let o=JSON.stringify(t);La().debug("posting",o);let r=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||La().error({status:r.status,body:await r.text()})})),e}i(gd,"getDispatcher");async function fd(n,e,t,o){g("policy.inbound.moesif-analytics"),ri=e.log;let r=Aa(),s=Object.assign(ld,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=s.logRequestBody?await ka(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=gd(s.applicationId),d=n.headers.get("true-client-ip"),p=oi.get(e)??{},h={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Sa(n.headers)},y=s.logResponseBody?await ka(u,e):void 0,v={time:Aa(),status:u.status,headers:Sa(u.headers),body:y},R={request:h,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:cd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(fd,"MoesifInboundPolicy");async function _a(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(_a,"loadSubscription");async function Na(n,e,t,o,r){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Na,"consumeSubcriptionQuotas");var hd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Hn(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Hn,"validateMeters");function Da(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=rt(n),o=[];for(let r of t)hd.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Da,"parseAllowedSubscriptionStatuses");function Ma(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}i(Ma,"compareMeters");var ii=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return re.get(e,Dt)}static setMeters(e,t){Hn(t,"setMeters");let o=re.get(e,Mt)??{};Object.assign(o,t),re.set(e,Mt,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=Ge(this.options.meterOnStatusCodes),s=re.get(t,Mt),a={...this.options.meters,...s};Hn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Da(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=re.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=re.get(N,Mt),H={...this.options.meters,...z};if(Hn(H,this.policyName),r.includes(R.status)&&S&&H){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify(H)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:q}=Ma(S.meters,H);if(q&&Object.keys(q).length>0){let V=Object.keys(q);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Na(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await _a(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),re.set(t,Dt,p));let h=re.get(t,Dt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(h.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(h.meters[R].available<=0&&!o)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};async function $n(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await be({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i($n,"getClientCredentialsAccessToken");var St=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{i(this,"OpenFGAError")}},Fn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new m("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let s=new Headers(o.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:r?JSON.stringify(r):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new St("unknown",`Unknown error. Status: ${c.status}`):new St(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var Ua="X-OpenFGA-Client-Method",qa="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Fn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Xt(o,Ua,"BatchCheck"),Xt(o,qa,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,o)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof St)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,Ua,"ListRelations"),Xt(c,qa,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Za=Symbol("openfga-authz-context-data"),At=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];re.set(e,Za,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let o=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=re.get(t,Za);if(!r||r.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new K(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let s=await $n({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ha=["us1","eu1","au1"],si=class extends At{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ha.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ha.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var yd=i(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var ai=class extends At{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as bd}from"jose";var ui,wd=i(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ui)try{ui=await bd(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:ui,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var ci="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",$a="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var li=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let s=Rd(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Pd(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Xe(this.policyName,r),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),o&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{o&&(R+=`${A} - allowed: ${N} value: ${h.meters[A]??0}
81
- `),(h.meters[A]??0)>=N&&v.push(A)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",R),v.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(A,N,S)=>{if(o&&S.log.debug(`QuotaInboundPolicy: backend response - ${A.status}: ${A.statusText}`),!s.quotaOnStatusCodes.includes(A.status))return;let F=re.get(S,ci),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};o&&S.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let H=p.setQuota(d,z,S.requestId);S.waitUntil(H)})}catch(s){r.error(s),t.log.error(s)}return e}static setMeters(e,t){let o=re.get(e,ci)??{};Object.assign(o,t),re.set(e,ci,o)}static getUsage(e,t){let o=re.get(e,`${$a}-${t}`);if(o===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return o}static#e(e,t,o){re.set(e,`${$a}-${t}`,o)}};function Rd(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Ge(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}i(Rd,"validateAndParseOptions");function Pd(n,e){return encodeURIComponent(`${e}-${n}`)}i(Pd,"processKey");var Fa=ye("zuplo:policies:RateLimitInboundPolicy"),ja=i(async(n,e,t,o)=>{let r=Q.getLogger(e),s=i((H,C)=>{let q={};return(!H||H==="retry-after")&&(q[Tt]=C.toString()),E.tooManyRequests(n,e,void 0,q)},"rateLimited"),u=await xt(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Xe(o,r),v=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${o}/${c}`,R=await se(o,void 0,t),A=new ie(R,e),N=h.getCountAndUpdateExpiry(v,d,e.requestId),S;i(async()=>{let H=await N;if(H.count>l){let C=Date.now()+H.ttlSeconds*1e3;A.put(v,C,H.ttlSeconds),Fa(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${v}' (async mode)`),S=s(p,H.ttlSeconds)}},"asyncCheck")();let z=await A.get(v);if(z!==void 0&&z>Date.now()){Fa(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${v}' (async mode)`);let H=Math.round((z-Date.now())/1e3);return s(p,H)}return e.addResponseSendingHook(async H=>S??H),n},"AsyncRateLimitInboundPolicyImpl");var za=ye("zuplo:policies:RateLimitInboundPolicy"),Id="strict",Ba=i(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??Id)==="async")return ja(n,e,t,o);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Tt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await xt(o,t)(n,e,o),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,v=t.headerMode??"retry-after",R=Xe(o,a),N=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${o}/${p}`,S=await R.getCountAndUpdateExpiry(N,y,e.requestId);return S.count>h?(za(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(v,S.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;za(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var di;function Ga(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}i(Ga,"headersToNameValuePairs");function Ed(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}i(Ed,"queryToNameValueParis");function xd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(xd,"parseIntOrUndefined");var Va={};async function Td(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,s=Date.now();return di||(di={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ze(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ze(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:di,entries:[{startedDateTime:r.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ga(n.headers),queryString:Ed(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ga(a.headers),content:{size:xd(n.headers.get("content-length"))}}}]}}},d=Va[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",v=await Z.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${v.status}: '${await v.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),Va[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Td,"ReadmeMetricsInboundPolicy");var vd=i(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return r.forEach(u=>{s.delete(u)}),new ne(n,{headers:s})},"RemoveHeadersInboundPolicy");var Cd=i(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let s=o?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Od=i(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return r.forEach(u=>{s.searchParams.delete(u)}),new ne(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Sd=i(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),s=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(s,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Wa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ad=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),s=r!==null?parseInt(r):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Wa():s&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?Wa():n},"RequestSizeLimitInboundPolicy");var kt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Lt=i((n,e,t,o,r)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Gn(t,o,r,c.name),p=ge.instance.schemaValidator[d],h=p(e[c.name]),y=pi(p.errors);h||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),pi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ja(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=E.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",v,[o],y),Le(t.validateBody))return R}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?v:void 0}let r=e.headers.get("Content-Type"),s=r.indexOf(";");s>-1&&(r=r.substring(0,s));let a=Vn(n.route.path,e.method,r),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[o],[y]),Le(t.validateBody)?v:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=pi(l),h=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[o],p),Le(t.validateBody))return h}i(Ja,"handleBodyValidation");function Ka(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=kt(n),s=Lt(r.filter(a=>a.in==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Ka,"handleHeadersValidation");function Qa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=kt(n),r=Lt(o.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validatePathParameters))return a}}i(Qa,"handlePathParameterValidation");function Ya(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=kt(n),r=Lt(o.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:r.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,r.invalidValues,r.errors),Le(t.validateQueryParameters))return a}}i(Ya,"handleQueryParameterValidation");var Xa=i(async(n,e,t)=>{g("policy.inbound.request-validation");let o=Ya(e,n,t);if(o!==void 0||(o=Qa(e,n,t),o!==void 0)||(o=Ka(e,n,t),o!==void 0))return o;let r=await Ja(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),kd=Xa;var Ld=i(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!r.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var _d=i(async(n,e,t)=>(g("policy.inbound.set-body"),new ne(n,{body:t.body})),"SetBodyInboundPolicy");var Nd=i(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new ne(n,{headers:s})},"SetHeadersInboundPolicy");var Dd=i(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let s=o.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Md=i(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new ne(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ud=i(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var qd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Zd=i(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await qd(t.sleepInMs),n},"SleepInboundPolicy");var Hd=i(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,r,o);if(s instanceof Response)return s;if(!(s instanceof ne))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${o}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var $d=i(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await se(o,void 0,t),s=new ie(r,e),a=await s.get(o);if(!a){let u=await Fd(t,e);s.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Fd(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let s=await o.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Fd,"getAccessToken");var eu="https://accounts.google.com/o/oauth2/token",mi,jd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),mi||(mi=await Te.init(t.serviceAccountJson));let r={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(o,void 0,t),a=new ie(s,e),u=await a.get(o);if(!u){let c=await De({serviceAccount:mi,audience:eu,payload:r}),l=await In(eu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var zd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Bd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],gi,Gd=i(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Bd.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}gi||(gi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ze(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${o}`);let a=await se(o,void 0,t),u=new ie(a,e),c={uid:s,claims:r},l=await ut(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:gi,audience:zd,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Bs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var tn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let o=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await se("zuplo-token",void 0,t),s=await o.get(r);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await $n({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var tu="service-account-id-token",fi=class extends ce{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new je(this.cacheName):o=new ie(this.cacheName,t);let r=await o.get(tu);if(!r){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await tn.getIDToken(t,{audience:s}),u=await js(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await zs({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");r=l.token,o.put(tu,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${r}`),e}};var hi,Vd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),hi||(hi=await Te.init(t.serviceAccountJson));let r=await De({serviceAccount:hi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var nu="https://www.googleapis.com/oauth2/v4/token",yi,Wd=i(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),yi||(yi=await Te.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=rt(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let s=await se(o,void 0,t),a;t.useMemoryCacheOnly?a=new je(s):a=new ie(s,e);let u=await a.get(o);if(!u){let c=await De({serviceAccount:yi,audience:nu,payload:r}),l=await In(nu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Jd=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(r))return n;let{errors:a}=t.validator.default;if(!a)throw new K("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return E.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ou=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=i((R,A)=>e(R,"name",{value:A,configurable:!0}),"__name"),r=i((R,A)=>i(function(){return A||(0,R[t(R)[0]])((A={exports:{}}).exports,A),A.exports},"__require"),"__commonJS"),s=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var A={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(S,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(S,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(S,F,z){return S},"updateTag")},N=o(function(S){return Object.assign({},A,S)},"buildOptions");R.buildOptions=N,R.defaultOptions=A}}),a=r({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var A=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=A+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S="["+A+"]["+N+"]*",F=new RegExp("^"+S+"$"),z=o(function(C,q){let V=[],j=q.exec(C);for(;j;){let x=[];x.startIndex=q.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=q.exec(C)}return V},"getAllMatches"),H=o(function(C){let q=F.exec(C);return!(q===null||typeof q>"u")},"isName");R.isExist=function(C){return typeof C<"u"},R.isEmptyObject=function(C){return Object.keys(C).length===0},R.merge=function(C,q,V){if(q){let j=Object.keys(q),x=j.length;for(let I=0;I<x;I++)V==="strict"?C[j[I]]=[q[j[I]]]:C[j[I]]=q[j[I]]}},R.getValue=function(C){return R.isExist(C)?C:""},R.isName=H,R.getAllMatches=z,R.nameRegexp=S}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,A){"use strict";var N=class{static{i(this,"XmlNode")}static{o(this,"XmlNode")}constructor(S){this.tagname=S,this.child=[],this[":@"]={}}add(S,F){S==="__proto__"&&(S="#__proto__"),this.child.push({[S]:F})}addChild(S){S.tagname==="__proto__"&&(S.tagname="#__proto__"),S[":@"]&&Object.keys(S[":@"]).length>0?this.child.push({[S.tagname]:S.child,":@":S[":@"]}):this.child.push({[S.tagname]:S.child})}};A.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,A){var N=a();function S(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,Ce="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&H(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&C(x,I))I+=8;else if(J&&q(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:Ce+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(S,"readDocType"),o(S,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),o(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),o(z,"isComment");function H(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="N"&&x[I+4]==="T"&&x[I+5]==="I"&&x[I+6]==="T"&&x[I+7]==="Y"}i(H,"isEntity"),o(H,"isEntity");function C(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(C,"isElement"),o(C,"isElement");function q(x,I){return x[I+1]==="!"&&x[I+2]==="A"&&x[I+3]==="T"&&x[I+4]==="T"&&x[I+5]==="L"&&x[I+6]==="I"&&x[I+7]==="S"&&x[I+8]==="T"}i(q,"isAttlist"),o(q,"isAttlist");function V(x,I){return x[I+1]==="!"&&x[I+2]==="N"&&x[I+3]==="O"&&x[I+4]==="T"&&x[I+5]==="A"&&x[I+6]==="T"&&x[I+7]==="I"&&x[I+8]==="O"&&x[I+9]==="N"}i(V,"isNotation"),o(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),o(j,"validateEntityName"),A.exports=S}}),l=r({"../../node_modules/strnum/strnum.js"(R,A){var N=/^[-+]?0x[a-fA-F0-9]+$/,S=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(C,q={}){if(q=Object.assign({},F,q),!C||typeof C!="string")return C;let V=C.trim();if(q.skipLike!==void 0&&q.skipLike.test(V))return C;if(q.hex&&N.test(V))return Number.parseInt(V,16);{let j=S.exec(V);if(j){let x=j[1],I=j[2],M=H(j[3]),le=j[4]||j[6];if(!q.leadingZeros&&I.length>0&&x&&V[2]!==".")return C;if(!q.leadingZeros&&I.length>0&&!x&&V[1]!==".")return C;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?q.eNotation?J:C:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:C:I?M===X||x+M===X?J:C:V===X||V===x+X?J:C}}else return C}}i(z,"toNumber"),o(z,"toNumber");function H(C){return C&&C.indexOf(".")!==-1&&(C=C.replace(/0+$/,""),C==="."?C="0":C[0]==="."?C="0"+C:C[C.length-1]==="."&&(C=C.substr(0,C.length-1))),C}i(H,"trimZeros"),o(H,"trimZeros"),A.exports=z}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,A){"use strict";var N=a(),S=u(),F=c(),z=l(),H=class{static{i(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=C,this.parseXml=I,this.parseTextData=q,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function C(P){let T=Object.keys(P);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(C,"addExternalEntities"),o(C,"addExternalEntities");function q(P,T,L,B,_,D,ee){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ee||(P=this.replaceEntitiesValue(P));let $=this.options.tagValueProcessor(T,P,L,_,D);return $==null?P:typeof $!=typeof P||$!==P?$:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(q,"parseTextData"),o(q,"parseTextData");function V(P){if(this.options.removeNSPrefix){let T=P.split(":"),L=P.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(P=L+T[1])}return P}i(V,"resolveNameSpace"),o(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(P,T,L){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=N.getAllMatches(P,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let $=this.resolveNameSpace(B[ee][1]),U=B[ee][4],pe=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(pe=this.options.transformAttributeName(pe)),pe==="__proto__"&&(pe="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let oe=this.options.attributeValueProcessor($,U,T);oe==null?D[pe]=U:typeof oe!=typeof U||oe!==U?D[pe]=oe:D[pe]=me(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[pe]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),o(x,"buildAttributesMap");var I=o(function(P){P=P.replace(/\r\n?/g,`
82
- `);let T=new S("!xml"),L=T,B="",_="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let $=b(P,">",D,"Closing Tag is not closed."),U=P.substring(D+2,$).trim();if(this.options.removeNSPrefix){let Se=U.indexOf(":");Se!==-1&&(U=U.substr(Se+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&(B=this.saveTextToParentTag(B,L,_));let pe=_.substring(_.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let oe=0;pe&&this.options.unpairedTags.indexOf(pe)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=$}else if(P[D+1]==="?"){let $=O(P,D,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new S($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,_,$.tagName)),this.addChild(L,U,_)}D=$.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let $=b(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=P.substring(D+4,$-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=$}else if(P.substr(D+1,2)==="!D"){let $=F(P,D);this.docTypeEntities=$.entities,D=$.i}else if(P.substr(D+1,2)==="!["){let $=b(P,"]]>",D,"CDATA is not closed.")-2,U=P.substring(D+9,$);B=this.saveTextToParentTag(B,L,_);let pe=this.parseTextData(U,L.tagname,_,!0,!1,!0,!0);pe==null&&(pe=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):L.add(this.options.textNodeName,pe),D=$+2}else{let $=O(P,D,this.options.removeNSPrefix),U=$.tagName,pe=$.rawTagName,oe=$.tagExp,Se=$.attrExpPresent,Ci=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let Oi=L;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),U!==T.tagname&&(_+=_?"."+U:U),this.isItStopNode(this.options.stopNodes,_,U)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=$.closeIndex;else{let Bn=this.readStopNodeData(P,pe,Ci+1);if(!Bn)throw new Error(`Unexpected end of ${pe}`);D=Bn.i,Oe=Bn.tagContent}let zn=new S(U);U!==oe&&Se&&(zn[":@"]=this.buildAttributesMap(oe,_,U)),Oe&&(Oe=this.parseTextData(Oe,U,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),zn.add(this.options.textNodeName,Oe),this.addChild(L,zn,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),_=_.substr(0,_.length-1),oe=U):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Oe=new S(U);U!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new S(U);this.tagsNodeStack.push(L),U!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,U)),this.addChild(L,Oe,_),L=Oe}B="",D=Ci}}else B+=P[D];return T.child},"parseXml");function M(P,T,L){let B=this.options.updateTag(T.tagname,L,T[":@"]);B===!1||(typeof B=="string"&&(T.tagname=B),P.addChild(T))}i(M,"addChild"),o(M,"addChild");var le=o(function(P){if(this.options.processEntities){for(let T in this.docTypeEntities){let L=this.docTypeEntities[T];P=P.replace(L.regx,L.val)}for(let T in this.lastEntities){let L=this.lastEntities[T];P=P.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let L=this.htmlEntities[T];P=P.replace(L.regex,L.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function J(P,T,L,B){return P&&(B===void 0&&(B=Object.keys(T.child).length===0),P=this.parseTextData(P,T.tagname,L,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&T.add(this.options.textNodeName,P),P=""),P}i(J,"saveTextToParentTag"),o(J,"saveTextToParentTag");function X(P,T,L){let B="*."+L;for(let _ in P){let D=P[_];if(B===D||T===D)return!0}return!1}i(X,"isItStopNode"),o(X,"isItStopNode");function Ce(P,T,L=">"){let B,_="";for(let D=T;D<P.length;D++){let ee=P[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===L[0])if(L[1]){if(P[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),o(Ce,"tagExpWithClosingIndex");function b(P,T,L,B){let _=P.indexOf(T,L);if(_===-1)throw new Error(B);return _+T.length-1}i(b,"findClosingIndex"),o(b,"findClosingIndex");function O(P,T,L,B=">"){let _=Ce(P,T+1,B);if(!_)return;let D=_.data,ee=_.index,$=D.search(/\s/),U=D,pe=!0;$!==-1&&(U=D.substring(0,$),D=D.substring($+1).trimStart());let oe=U;if(L){let Se=U.indexOf(":");Se!==-1&&(U=U.substr(Se+1),pe=U!==_.data.substr(Se+1))}return{tagName:U,tagExp:D,closeIndex:ee,attrExpPresent:pe,rawTagName:oe}}i(O,"readTagExp"),o(O,"readTagExp");function G(P,T,L){let B=L,_=1;for(;L<P.length;L++)if(P[L]==="<")if(P[L+1]==="/"){let D=b(P,">",L,`${T} is not closed`);if(P.substring(L+2,D).trim()===T&&(_--,_===0))return{tagContent:P.substring(B,L),i:D};L=D}else if(P[L+1]==="?")L=b(P,"?>",L+1,"StopNode is not closed.");else if(P.substr(L+1,3)==="!--")L=b(P,"-->",L+3,"StopNode is not closed.");else if(P.substr(L+1,2)==="![")L=b(P,"]]>",L,"StopNode is not closed.")-2;else{let D=O(P,L,">");D&&((D&&D.tagName)===T&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(G,"readStopNodeData"),o(G,"readStopNodeData");function me(P,T,L){if(T&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:z(P,L)}else return N.isExist(P)?P:""}i(me,"parseValue"),o(me,"parseValue"),A.exports=H}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function A(H,C){return N(H,C)}i(A,"prettify"),o(A,"prettify");function N(H,C,q){let V,j={};for(let x=0;x<H.length;x++){let I=H[x],M=S(I),le="";if(q===void 0?le=M:le=q+"."+M,M===C.textNodeName)V===void 0?V=I[M]:V+=""+I[M];else{if(M===void 0)continue;if(I[M]){let J=N(I[M],C,le),X=z(J,C);I[":@"]?F(J,I[":@"],le,C):Object.keys(J).length===1&&J[C.textNodeName]!==void 0&&!C.alwaysCreateTextNode?J=J[C.textNodeName]:Object.keys(J).length===0&&(C.alwaysCreateTextNode?J[C.textNodeName]="":J=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(J)):C.isArray(M,le,X)?j[M]=[J]:j[M]=J}}}return typeof V=="string"?V.length>0&&(j[C.textNodeName]=V):V!==void 0&&(j[C.textNodeName]=V),j}i(N,"compress"),o(N,"compress");function S(H){let C=Object.keys(H);for(let q=0;q<C.length;q++){let V=C[q];if(V!==":@")return V}}i(S,"propName"),o(S,"propName");function F(H,C,q,V){if(C){let j=Object.keys(C),x=j.length;for(let I=0;I<x;I++){let M=j[I];V.isArray(M,q+"."+M,!0,!0)?H[M]=[C[M]]:H[M]=C[M]}}}i(F,"assignAttributes"),o(F,"assignAttributes");function z(H,C){let{textNodeName:q}=C,V=Object.keys(H).length;return!!(V===0||V===1&&(H[q]||typeof H[q]=="boolean"||H[q]===0))}i(z,"isLeafTag"),o(z,"isLeafTag"),R.prettify=A}}),h=r({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var A=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},N,O);let G=[],me=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let T=0;T<b.length;T++)if(b[T]==="<"&&b[T+1]==="?"){if(T+=2,T=F(b,T),T.err)return T}else if(b[T]==="<"){let L=T;if(T++,b[T]==="!"){T=z(b,T);continue}else{let B=!1;b[T]==="/"&&(B=!0,T++);let _="";for(;T<b.length&&b[T]!==">"&&b[T]!==" "&&b[T]!==" "&&b[T]!==`
83
- `&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let $;return _.trim().length===0?$="Invalid space after '<'.":$="Tag '"+_+"' is an invalid name.",M("InvalidTag",$,X(b,T))}let D=q(b,T);if(D===!1)return M("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,T));let ee=D.value;if(T=D.index,ee[ee.length-1]==="/"){let $=T-ee.length;ee=ee.substring(0,ee.length-1);let U=j(ee,O);if(U===!0)me=!0;else return M(U.err.code,U.err.msg,X(b,$+U.err.line))}else if(B)if(D.tagClosed){if(ee.trim().length>0)return M("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let $=G.pop();if(_!==$.tagName){let U=X(b,$.tagStartPos);return M("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(P=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let $=j(ee,O);if($!==!0)return M($.err.code,$.err.msg,X(b,T-ee.length+$.err.line));if(P===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let $=I(b,T);if($==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=$}else if(P===!0&&!S(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(S(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(b){return b===" "||b===" "||b===`
84
- `||b==="\r"}i(S,"isWhiteSpace"),o(S,"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 H='"',C="'";function q(b,O){let G="",me="",P=!1;for(;O<b.length;O++){if(b[O]===H||b[O]===C)me===""?me=b[O]:me!==b[O]||(me="");else if(b[O]===">"&&me===""){P=!0;break}G+=b[O]}return me!==""?!1:{value:G,index:O,tagClosed:P}}i(q,"readAttributeStr"),o(q,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(b,O){let G=A.getAllMatches(b,V),me={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return M("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Ce(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return M("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Ce(G[P]));if(G[P][3]===void 0&&!O.allowBooleanAttributes)return M("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Ce(G[P]));let T=G[P][2];if(!le(T))return M("InvalidAttr","Attribute '"+T+"' is an invalid name.",Ce(G[P]));if(!me.hasOwnProperty(T))me[T]=1;else return M("InvalidAttr","Attribute '"+T+"' is repeated.",Ce(G[P]))}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 A.isName(b)}i(le,"validateAttrName"),o(le,"validateAttrName");function J(b){return A.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 Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),o(Ce,"getPositionFromMatch")}}),y=r({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,A){var{buildOptions:N}=s(),S=d(),{prettify:F}=p(),z=h(),H=class{static{i(this,"XMLParser")}static{o(this,"XMLParser")}constructor(C){this.externalEntities={},this.options=N(C)}parse(C,q){if(typeof C!="string")if(C.toString)C=C.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(q){q===!0&&(q={});let x=z.validate(C,q);if(x!==!0)throw Error(`${x.err.msg}:${x.err.line}:${x.err.col}`)}let V=new S(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(C);return this.options.preserveOrder||j===void 0?j:F(j,this.options)}addEntity(C,q){if(q.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(C.indexOf("&")!==-1||C.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(q==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[C]=q}};A.exports=H}});let v=y();return new v(n)},"getXmlParser");var bi=class extends We{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?Ge(e.parseOnStatusCodes):void 0,this.parser=ou({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 wi=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 nn=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),Je().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var ru=10,iu=3e4,Ri=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=iu,this.#o=ru}else{let o=t;this.#n=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:iu,this.#o=ru}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 Kd(()=>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);Je().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 Kd(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(Kd,"waitUntilTrue");var Pi,_t=class{static{i(this,"RequestLoggerCore")}constructor(e,t){let r=(e.batchPeriodSeconds??.01)*1e3;this.#n=new nn(this.#t,{msDelay:r}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,o)=>{Pi=o;let r=Date.now();return o.addResponseSendingFinalHook(async s=>{let a={deploymentName:f.instance.deploymentName??"",instanceId:f.instance.instanceId,systemUserAgent:f.instance.systemUserAgent,requestStartTime:new Date(r),durationMs:Date.now()-r},u=await this.#e.generateLogEntry(s,t,o,a);this.#n.enqueue(u)}),t})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){Qd(t,this.#e.name)}},"#dispatch");#n};function Qd(n,e){if(!Pi){let o=Je(),r=te({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});o.waitUntil(r);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,Pi.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}i(Qd,"logError");var su="plugin.azure-blob-request-logger",Yd=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${f.instance.instanceId}.csv`,"defaultGenerateBlobName"),au,Ei=class extends Ie{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,g(su)}async initialize(e){new _t({name:su,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t=Xd(e[0]),o=tp(e,t),s=(this.#e.generateBlobName??Yd)(e);await np(o,this.#e,s)},"#dispatch")};function Xd(n){return Object.keys(n)}i(Xd,"getHeaders");function ep(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
85
- `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(ep,"escapeCsvValue");function tp(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(ep(a))}t.push(r.join(","))}return t.join(`
86
- `)}i(tp,"generateCsvContent");async function np(n,e,t){let{sasUrl:o}=e,r=o.split("?"),s=`${r[0]}/${t}?${r[1]}`;try{let a=await Z.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(Ii({message:a.statusText,status:a.status,details:await a.text()}),Ii({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Ii(a)}}i(np,"uploadToAzureBlobStorage");function Ii(n){if(!au){let t=Je(),o=te({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,au.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(Ii,"logError");var op="plugin.request-logger",xi=class extends Ie{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(op)}async initialize(e){new _t(this.#e,e)}#e};async function rp(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:o}=e,r=new URL(n,f.instance.zuploEdgeApiUrl),s=new Headers(e.headers);_e(s),s.set("Content-Type","application/json");let a={method:t,headers:s};o&&(a.body=JSON.stringify(o));let u=await Z.fetch(r,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(rp,"apiServices");var Ti=["sha-1","sha-256","sha-384","sha-512"],jn=class{static{i(this,"BaseCryptoBeta")}};var vi=class extends jn{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Ti.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Ti.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{Er as AWSLoggingPlugin,Rl as AmberfloMeteringInboundPolicy,Hr as AmberfloMeteringPolicy,El as ApiAuthKeyInboundPolicy,$r as ApiKeyInboundPolicy,Fr as AsertoAuthZInboundPolicy,kr as AuditLogDataStaxProvider,Lr as AuditLogPlugin,Ol as Auth0JwtInboundPolicy,Zc as AwsLambdaHandlerExtensions,Gr as AxiomaticsAuthZInboundPolicy,Ei as AzureBlobPlugin,nn as BackgroundDispatcher,Ri as BackgroundLoader,Sl as BasicAuthInboundPolicy,Ba as BasicRateLimitInboundPolicy,Y as BatchDispatch,Jr as BrownoutInboundPolicy,Hl as CachingInboundPolicy,$l as ChangeMethodInboundPolicy,Fl as ClearHeadersInboundPolicy,jl as ClearHeadersOutboundPolicy,zl as ClerkJwtInboundPolicy,Bl as CognitoJwtInboundPolicy,ti as ComplexRateLimitInboundPolicy,ed as CompositeInboundPolicy,td as CompositeOutboundPolicy,m as ConfigurationError,Oo as ContentTypes,re as ContextData,vi as CryptoBeta,nd as CurityPhantomTokenInboundPolicy,tr as DataDogLoggingPlugin,vr as DataDogMetricsPlugin,gr as DynaTraceLoggingPlugin,Sr as DynatraceMetricsPlugin,rd as FirebaseJwtInboundPolicy,id as FormDataToJsonInboundPolicy,sd as GeoFilterInboundPolicy,Ko as GoogleCloudLoggingPlugin,ir as Handler,E as HttpProblems,gn as HttpStatusCode,ce as InboundPolicy,ad as JWTScopeValidationInboundPolicy,hr as LokiLoggingPlugin,ht as LookupResult,ie as MemoryZoneReadThroughCache,ud as MockApiInboundPolicy,fd as MoesifInboundPolicy,ii as MonetizationInboundPolicy,si as OktaFGAAuthZInboundPolicy,yd as OktaJwtInboundPolicy,ai as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,We as OutboundPolicy,nt as ProblemResponseFormatter,wd as PropelAuthJwtInboundPolicy,li as QuotaInboundPolicy,Ba as RateLimitInboundPolicy,Td as ReadmeMetricsInboundPolicy,vd as RemoveHeadersInboundPolicy,Cd as RemoveHeadersOutboundPolicy,Od as RemoveQueryParamsInboundPolicy,Sd as ReplaceStringOutboundPolicy,xi as RequestLoggerPlugin,Ad as RequestSizeLimitInboundPolicy,Xa as RequestValidationInboundPolicy,Ld as RequireOriginInboundPolicy,Zt as ResponseSendingEvent,Ht as ResponseSentEvent,k as RuntimeError,un as SYSTEM_LOGGER,kd as SchemaBasedRequestValidation,He as SemanticAttributes,wi as ServiceProviderImpl,_d as SetBodyInboundPolicy,Nd as SetHeadersInboundPolicy,Dd as SetHeadersOutboundPolicy,Md as SetQueryParamsInboundPolicy,Ud as SetStatusOutboundPolicy,Zd as SleepInboundPolicy,ya as StripeMonetizationPlugin,Yt as StripeWebhookVerificationInboundPolicy,wr as SumoLogicLoggingPlugin,Hd as SupabaseJwtInboundPolicy,Ue as SystemRouteName,Ut as TelemetryPlugin,$d as UpstreamAzureAdServiceAuthInboundPolicy,jd as UpstreamFirebaseAdminAuthInboundPolicy,Gd as UpstreamFirebaseUserAuthInboundPolicy,fi as UpstreamGcpFederatedAuthInboundPolicy,Vd as UpstreamGcpJwtInboundPolicy,Wd as UpstreamGcpServiceAuthInboundPolicy,Pr as VMWareLogInsightLoggingPlugin,Jd as ValidateJsonSchemaInbound,bi as XmlToJsonOutboundPolicy,Nt as ZoneCache,ne as ZuploRequest,tn as ZuploServices,rp as apiServices,Hc as awsLambdaHandler,Re as environment,Gn as getIdForParameterSchema,du as getIdForRefSchema,Vn as getIdForRequestBodySchema,lu as getRawOperationDataIdentifierName,ko as httpStatuses,Wc as openApiSpecHandler,Kc as redirectHandler,pu as sanitizedIdentifierName,So as serialize,pd as setMoesifContext,g as trackFeature,Xc as urlForwardHandler,tl as urlRewriteHandler,nl as webSocketHandler,ol as webSocketPipelineHandler,Qc as zuploServiceProxy};
80
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(xl,"validateComputedSignature");function Tl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Tl,"parseHeader");function vl(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(vl,"secureCompare");async function Cl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Ho[s[u]];return a.join("")}i(Cl,"computeHMACSignatureAsync");var Ho=new Array(256);for(let n=0;n<Ho.length;n++)Ho[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await fa(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ha(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(ha,"isStripeWebhookEvent");var Ol={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o},"getUpcomingInvoice")},Mn=Ol;var $o="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ya="My API Key";async function ba({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,$o);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ya,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ba,"createConsumer");async function wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,$o);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ya,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({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 f="Error creating API Key Consumer";throw s.log.error(f,p),new k(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(wa,"createConsumerInvite");async function Ra({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,$o);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ra,"deleteConsumer");async function Pa({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ft(p))throw new K("No Zuplo JWT token set.");let y=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(Pa,"createSubscription");async function Pt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Pt,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(It,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function qn(n){return n.replaceAll("_","-")}i(qn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function Zo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),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!==h.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.`+Ie});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 ba({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Mn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await wa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),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=qn(t.data.object.status),f;l&&d&&(f={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:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Pa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await Ra({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Xe})}i(Zo,"onCustomerSubscriptionCreated");async function Fo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),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!==h.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.`+Ie});try{let a=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.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. `+Ie})}return E.ok(n,e,{title:Xe})}i(Fo,"onCustomerSubscriptionDeleted");async function jo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),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!==h.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.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=qn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.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. `+Ie})}return E.ok(n,e,{title:Xe})}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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Mn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.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 Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.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. `+Ie})}return E.ok(n,e,{title:Xe})}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 It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.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. `+Ie})}return E.ok(n,e,{title:Xe})}}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."+Ie})}i(jo,"onCustomerSubscriptionUpdated");var Ia=class extends pn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!Sl(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ha(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. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Zo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await jo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Fo(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.`+Ie})}},"stripeWebhookHandler"),s=_s({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Sl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Sl,"isMetricsRegion");var xa=new WeakMap,Ea={},zo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){xa.set(e,t)}};async function Al(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ve(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=xa.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=$e(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=Ea[t.apiKey];if(!f){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";f=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await H.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${A.message}`),A}}),Ea[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Al,"AmberfloMeteringInboundPolicy");async function ct(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(ct,"sha256");var Ta=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=Ta.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,Ta.set(n,r)),r}i(se,"getPolicyCacheName");var va="key-metadata-cache-type";function kl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(kl,"getKeyValue");async function Bo(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(N=>o.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=kl(a,o);if(!u||u==="")return s("No key present");let c=await Ll(u),l=await se(r,void 0,o),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==va&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(f)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:va,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,o.cacheTtlSeconds),n}i(Bo,"ApiKeyInboundPolicy");async function Ll(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(Ll,"hashValue");var _l=Bo;var Ca=Symbol("aserto-authz-resource-context"),Go=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){te.set(e,Ca,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 r=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 o=te.get(t,Ca),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?$e(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await 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?r(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),r("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 Dl,jwtVerify as Sa}from"jose";import{createLocalJWKSet as Nl}from"jose";var Vo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Wo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Nl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await H.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Et("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 Et("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Oa(n,e,t){let r=new Vo(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Oa,"createRemoteJWKSet");var Et=class extends k{static{i(this,"JWKSError")}},Wo=class extends Et{static{i(this,"JWKSNoMatchingKey")}},Jo=class extends Et{static{i(this,"JWKSTimeout")}};var Un={},Ml=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Un[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new ie(a,e);Un[r.jwkUrl]=Oa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Un[r.jwkUrl]=Dl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Sa(t,Un[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),ql=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:r}=await Sa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Re=i(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Ml(r,e):ql,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",f=d[p];return f?(n.user={sub:f,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ul=i(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Re(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Hn=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 Ko=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Hn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Hl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===f&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function $n(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i($n,"extractDateElements");function Aa(n,e){return new Date(n,e+1,0).getDate()}i(Aa,"getDaysInMonth");function Qo(n,e){return n<=e?e-n:6-n+e+1}i(Qo,"getDaysBetweenWeekdays");var Zn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=Aa(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?Qo(d,p):Qo(p,d);l=e==="next"?o+f:o-f,(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=$n(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=$n(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=$n(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var $l={min:0,max:59},Zl={min:0,max:59},Fl={min:0,max:23},jl={min:1,max:31},zl={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"}},Bl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Gl={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function Yo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Gl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Zn({seconds:lt(t,$l),minutes:lt(r,Zl),hours:lt(o,Fl),days:lt(s,jl),months:new Set(Array.from(lt(a,zl)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Bl)).map(c=>c%7))})}i(Yo,"parseCronExpression");var Xo=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Yo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Yo(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=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 Vl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Wl(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(Wl,"digestMessage");var Jl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Wl(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Kl(n,e,t,r){g("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Jl(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 f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Vl.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Kl,"CachingInboundPolicy");var Ql=i(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Yl=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var Xl=i(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var ed=i(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Re(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var td=i(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return Re(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Fn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},ei=class extends Fn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ti=class extends Fn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function nd(n,e){if(Ts(n))throw new ei(e)}i(nd,"throwIfUndefinedOrNull");function ka(n,e){if(nd(n,e),!xe(n))throw new ti(e,"string")}i(ka,"throwIfNotString");var ni=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},rd=500,ri=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){ka(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},rd);let a,u=new Headers({"content-type":"application/json"});_e(u,o);try{a=await H.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},xt;function et(n,e){if(xt)return xt;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),xt=new ni,xt;let{redisURL:t,authApiJWT:r}=h.instance;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(r))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return xt=new ri(t),xt}i(et,"getRateLimitClient");var od=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 Tt(n,e){return{function:ud(e,"RateLimitInboundPolicy",n),user:sd,ip:id,all:ad}[e.rateLimitBy??"ip"]}i(Tt,"getRateLimitByFunctions");var id=i(async n=>({key:`ip-${od(n)}`}),"getIP"),sd=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),ad=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function ud(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(ud,"wrapUserFunction");var vt="Retry-After";var La=be("zuplo:policies:ComplexRateLimitInboundPolicy"),oi=Symbol("complex-rate-limit-counters"),ii=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=te.get(e,oi)??{};Object.assign(r,t),te.set(e,oi,t)}static getIncrements(e){return te.get(e,oi)??{}}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[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=et(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[vt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Tt(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);La(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:f,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){o.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:f,limit:N})),v=await s.multiCount(y,t.requestId);return cd(v,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;La(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function cd(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(cd,"findOverLimits");var ld=i(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Ft(t.policies,o?.routeData.policies);return Gr(s)(n,e)},"CompositeInboundPolicy");var dd=i(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new m(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=jt(r.policies,s?.routeData.policies);return Vr(a)(n,e,t)},"CompositeOutboundPolicy");var pd=i(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return E.unauthorized(n,e,{detail:"No authorization header"});let s=md(o);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,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 md(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(md,"getToken");var gd=i(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Re(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var fd=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ct="__unknown__",hd=i(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:St(t.allow?.countries,"allow.countries",r),regionCodes:St(t.allow?.regionCodes,"allow.regionCode",r),asns:St(t.allow?.asns,"allow.asOrganization",r)},block:{countries:St(t.block?.countries,"block.countries",r),regionCodes:St(t.block?.regionCodes,"block.regionCode",r),asns:St(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Ct,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ct,u=e.incomingRequestProperties.asn?.toString()??Ct,c=o.ignoreUnknown&&s===Ct,l=o.ignoreUnknown&&a===Ct,d=o.ignoreUnknown&&u===Ct,p=o.allow.countries,f=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ot(n,e,r,s,a,u);let v=o.block.countries,R=o.block.regionCodes,A=o.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ot(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ot(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ot,"blockedResponse");function St(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(St,"toLowerStringArray");var yd=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var bd=i(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return si(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return si(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),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 _a(a[u])}else return a.length>0?_a(a[0]):si(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function _a(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(_a,"generateResponse");var si=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return E.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var wd="Incoming",Rd={logRequestBody:!0,logResponseBody:!0};function Na(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Na,"headersToObject");function Da(){return new Date().toISOString()}i(Da,"timestamp");var ai=new WeakMap,Pd={};function Id(n,e){let t=ai.get(n);t||(t=Pd);let r=Object.assign({...t},e);ai.set(n,r)}i(Id,"setMoesifContext");async function Ma(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(Ma,"readBody");var Ed={},ui;function qa(){if(!ui)throw new k("Invalid State - no _lastLogger");return ui}i(qa,"getLastLogger");function xd(n){let e=Ed[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);qa().debug("posting",r);let o=await H.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||qa().error({status:o.status,body:await o.text()})})),e}i(xd,"getDispatcher");async function Td(n,e,t,r){g("policy.inbound.moesif-analytics"),ui=e.log;let o=Da(),s=Object.assign(Rd,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ma(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=xd(s.applicationId),d=n.headers.get("true-client-ip"),p=ai.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Na(n.headers)},y=s.logResponseBody?await Ma(u,e):void 0,v={time:Da(),status:u.status,headers:Na(u.headers),body:y},R={request:f,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:wd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(Td,"MoesifInboundPolicy");async function Ua(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ua,"loadSubscription");async function Ha(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Ha,"consumeSubcriptionQuotas");var vd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function jn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(jn,"validateMeters");function $a(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=it(n),r=[];for(let o of t)vd.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i($a,"parseAllowedSubscriptionStatuses");function Za(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Za,"compareMeters");var ci=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return te.get(e,Dt)}static setMeters(e,t){jn(t,"setMeters");let r=te.get(e,Mt)??{};Object.assign(r,t),te.set(e,Mt,r)}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 r=this.options.allowRequestsOverQuota??!1,o=Ve(this.options.meterOnStatusCodes),s=te.get(t,Mt),a={...this.options.meters,...s};jn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=$a(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=te.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=te.get(N,Mt),$={...this.options.meters,...z};if(jn($,this.policyName),o.includes(R.status)&&S&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify($)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:U}=Za(S.meters,$);if(U&&Object.keys(U).length>0){let V=Object.keys(U);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Ha(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ua(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`),te.set(t,Dt,p));let f=te.get(t,Dt);if(!f)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(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(f.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(f.meters[R].available<=0&&!r)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,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 r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(zn,"getClientCredentialsAccessToken");var At=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Bn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new m("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):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 At("unknown",`Unknown error. Status: ${c.status}`):new At(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var Fa="X-OpenFGA-Client-Method",ja="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Bn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Xt(r,Fa,"BatchCheck"),Xt(r,ja,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof At)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,Fa,"ListRelations"),Xt(c,ja,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var za=Symbol("openfga-authz-context-data"),kt=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];te.set(e,za,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=te.get(t,za);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new K(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await zn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ba=["us1","eu1","au1"],li=class extends kt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ba.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ba.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Cd=i(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Re(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var di=class extends kt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as Od}from"jose";var pi,Sd=i(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!pi)try{pi=await Od(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Re(n,e,{issuer:t.authUrl,secret:pi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var mi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Ga="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var gi=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=Ad(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=kd(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=et(this.policyName,o),f=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,f),r&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{r&&(R+=`${A} - allowed: ${N} value: ${f.meters[A]??0}
81
+ `),(f.meters[A]??0)>=N&&v.push(A)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",R),v.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(A,N,S)=>{if(r&&S.log.debug(`QuotaInboundPolicy: backend response - ${A.status}: ${A.statusText}`),!s.quotaOnStatusCodes.includes(A.status))return;let F=te.get(S,mi),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};r&&S.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let $=p.setQuota(d,z,S.requestId);S.waitUntil($)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=te.get(e,mi)??{};Object.assign(r,t),te.set(e,mi,r)}static getUsage(e,t){let r=te.get(e,`${Ga}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){te.set(e,`${Ga}-${t}`,r)}};function Ad(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new 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'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Ve(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Ad,"validateAndParseOptions");function kd(n,e){return encodeURIComponent(`${e}-${n}`)}i(kd,"processKey");var Va=be("zuplo:policies:RateLimitInboundPolicy"),Wa=i(async(n,e,t,r)=>{let o=Q.getLogger(e),s=i(($,C)=>{let U={};return(!$||$==="retry-after")&&(U[vt]=C.toString()),E.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await Tt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=et(r,o),v=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${r}/${c}`,R=await se(r,void 0,t),A=new ie(R,e),N=f.getCountAndUpdateExpiry(v,d,e.requestId),S;i(async()=>{let $=await N;if($.count>l){let C=Date.now()+$.ttlSeconds*1e3;A.put(v,C,$.ttlSeconds),Va(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),S=s(p,$.ttlSeconds)}},"asyncCheck")();let z=await A.get(v);if(z!==void 0&&z>Date.now()){Va(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let $=Math.round((z-Date.now())/1e3);return s(p,$)}return e.addResponseSendingHook(async $=>S??$),n},"AsyncRateLimitInboundPolicyImpl");var Ja=be("zuplo:policies:RateLimitInboundPolicy"),Ld="strict",Ka=i(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Ld)==="async")return Wa(n,e,t,r);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[vt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Tt(r,t)(n,e,r),p=d.key,f=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,v=t.headerMode??"retry-after",R=et(r,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${r}/${p}`,S=await R.getCountAndUpdateExpiry(N,y,e.requestId);return S.count>f?(Ja(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(v,S.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ja(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var fi;function Qa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Qa,"headersToNameValuePairs");function _d(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(_d,"queryToNameValueParis");function Nd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Nd,"parseIntOrUndefined");var Ya={};async function Dd(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return fi||(fi={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?$e(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?$e(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:fi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Qa(n.headers),queryString:_d(n.query)},response:{status:a.status,statusText:a.statusText,headers:Qa(a.headers),content:{size:Nd(n.headers.get("content-length"))}}}]}}},d=Ya[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",v=await H.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${v.status}: '${await v.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Ya[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Dd,"ReadmeMetricsInboundPolicy");var Md=i(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var qd=i(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Ud=i(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Hd=i(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Xa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),$d=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Xa():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Xa():n},"RequestSizeLimitInboundPolicy");var Lt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),_t=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Kn(t,r,o,c.name),p=ge.instance.schemaValidator[d],f=p(e[c.name]),y=hi(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),hi=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 eu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=E.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",v,[r],y),Le(t.validateBody))return R}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?v:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Qn(n.route.path,e.method,o),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?v:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=hi(l),f=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return f}i(eu,"handleBodyValidation");function tu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Lt(n),s=_t(o.filter(a=>a.in==="header"),r,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(tu,"handleHeadersValidation");function nu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(nu,"handlePathParameterValidation");function ru(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(ru,"handleQueryParameterValidation");var ou=i(async(n,e,t)=>{g("policy.inbound.request-validation");let r=ru(e,n,t);if(r!==void 0||(r=nu(e,n,t),r!==void 0)||(r=tu(e,n,t),r!==void 0))return r;let o=await eu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Zd=ou;var Fd=i(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var jd=i(async(n,e,t)=>(g("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var zd=i(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var Bd=i(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Gd=i(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Vd=i(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Wd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Jd=i(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Wd(t.sleepInMs),n},"SleepInboundPolicy");var Kd=i(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Re(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))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 '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Qd=i(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await se(r,void 0,t),s=new ie(o,e),a=await s.get(r);if(!a){let u=await Yd(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Yd(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Yd,"getAccessToken");var iu="https://accounts.google.com/o/oauth2/token",yi,Xd=i(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),yi||(yi=await Te.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(r,void 0,t),a=new ie(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:yi,audience:iu,payload:o}),l=await Tn(iu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var ep="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",tp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],bi,np=i(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(tp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}bi||(bi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=$e(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await se(r,void 0,t),u=new ie(a,e),c={uid:s,claims:o},l=await ct(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:bi,audience:ep,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Ks(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var tn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await se("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.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 r.put(o,d.access_token,d.expires_in-300),d.access_token}};var su="service-account-id-token",wi=class extends ce{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new ze(this.cacheName):r=new ie(this.cacheName,t);let o=await r.get(su);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await tn.getIDToken(t,{audience:s}),u=await Ws(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 Js({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(su,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ri,rp=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Ri||(Ri=await Te.init(t.serviceAccountJson));let o=await De({serviceAccount:Ri,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var au="https://www.googleapis.com/oauth2/v4/token",Pi,op=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Pi||(Pi=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=it(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await se(r,void 0,t),a;t.useMemoryCacheOnly?a=new ze(s):a=new ie(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Pi,audience:au,payload:o}),l=await Tn(au,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var ip=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new 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 uu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((R,A)=>e(R,"name",{value:A,configurable:!0}),"__name"),o=i((R,A)=>i(function(){return A||(0,R[t(R)[0]])((A={exports:{}}).exports,A),A.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var A={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(S,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(S,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(S,F,z){return S},"updateTag")},N=r(function(S){return Object.assign({},A,S)},"buildOptions");R.buildOptions=N,R.defaultOptions=A}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var A=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=A+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S="["+A+"]["+N+"]*",F=new RegExp("^"+S+"$"),z=r(function(C,U){let V=[],j=U.exec(C);for(;j;){let x=[];x.startIndex=U.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=U.exec(C)}return V},"getAllMatches"),$=r(function(C){let U=F.exec(C);return!(U===null||typeof U>"u")},"isName");R.isExist=function(C){return typeof C<"u"},R.isEmptyObject=function(C){return Object.keys(C).length===0},R.merge=function(C,U,V){if(U){let j=Object.keys(U),x=j.length;for(let I=0;I<x;I++)V==="strict"?C[j[I]]=[U[j[I]]]:C[j[I]]=U[j[I]]}},R.getValue=function(C){return R.isExist(C)?C:""},R.isName=$,R.getAllMatches=z,R.nameRegexp=S}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,A){"use strict";var N=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(S){this.tagname=S,this.child=[],this[":@"]={}}add(S,F){S==="__proto__"&&(S="#__proto__"),this.child.push({[S]:F})}addChild(S){S.tagname==="__proto__"&&(S.tagname="#__proto__"),S[":@"]&&Object.keys(S[":@"]).length>0?this.child.push({[S.tagname]:S.child,":@":S[":@"]}):this.child.push({[S.tagname]:S.child})}};A.exports=N}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,A){var N=a();function S(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,Ce="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&$(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&C(x,I))I+=8;else if(J&&U(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:Ce+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(S,"readDocType"),r(S,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),r(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),r(z,"isComment");function $(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($,"isEntity"),r($,"isEntity");function C(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(C,"isElement"),r(C,"isElement");function U(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(U,"isAttlist"),r(U,"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"),r(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),r(j,"validateEntityName"),A.exports=S}}),l=o({"../../node_modules/strnum/strnum.js"(R,A){var N=/^[-+]?0x[a-fA-F0-9]+$/,S=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(C,U={}){if(U=Object.assign({},F,U),!C||typeof C!="string")return C;let V=C.trim();if(U.skipLike!==void 0&&U.skipLike.test(V))return C;if(U.hex&&N.test(V))return Number.parseInt(V,16);{let j=S.exec(V);if(j){let x=j[1],I=j[2],M=$(j[3]),le=j[4]||j[6];if(!U.leadingZeros&&I.length>0&&x&&V[2]!==".")return C;if(!U.leadingZeros&&I.length>0&&!x&&V[1]!==".")return C;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?U.eNotation?J:C:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:C:I?M===X||x+M===X?J:C:V===X||V===x+X?J:C}}else return C}}i(z,"toNumber"),r(z,"toNumber");function $(C){return C&&C.indexOf(".")!==-1&&(C=C.replace(/0+$/,""),C==="."?C="0":C[0]==="."?C="0"+C:C[C.length-1]==="."&&(C=C.substr(0,C.length-1))),C}i($,"trimZeros"),r($,"trimZeros"),A.exports=z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,A){"use strict";var N=a(),S=u(),F=c(),z=l(),$=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=C,this.parseXml=I,this.parseTextData=U,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function C(P){let T=Object.keys(P);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(C,"addExternalEntities"),r(C,"addExternalEntities");function U(P,T,L,B,_,D,ee){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ee||(P=this.replaceEntitiesValue(P));let Z=this.options.tagValueProcessor(T,P,L,_,D);return Z==null?P:typeof Z!=typeof P||Z!==P?Z:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(U,"parseTextData"),r(U,"parseTextData");function V(P){if(this.options.removeNSPrefix){let T=P.split(":"),L=P.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(P=L+T[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(P,T,L){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=N.getAllMatches(P,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let Z=this.resolveNameSpace(B[ee][1]),q=B[ee][4],pe=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(pe=this.options.transformAttributeName(pe)),pe==="__proto__"&&(pe="#__proto__"),q!==void 0){this.options.trimValues&&(q=q.trim()),q=this.replaceEntitiesValue(q);let oe=this.options.attributeValueProcessor(Z,q,T);oe==null?D[pe]=q:typeof oe!=typeof q||oe!==q?D[pe]=oe:D[pe]=me(q,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[pe]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),r(x,"buildAttributesMap");var I=r(function(P){P=P.replace(/\r\n?/g,`
82
+ `);let T=new S("!xml"),L=T,B="",_="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let Z=b(P,">",D,"Closing Tag is not closed."),q=P.substring(D+2,Z).trim();if(this.options.removeNSPrefix){let Se=q.indexOf(":");Se!==-1&&(q=q.substr(Se+1))}this.options.transformTagName&&(q=this.options.transformTagName(q)),L&&(B=this.saveTextToParentTag(B,L,_));let pe=_.substring(_.lastIndexOf(".")+1);if(q&&this.options.unpairedTags.indexOf(q)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${q}>`);let oe=0;pe&&this.options.unpairedTags.indexOf(pe)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=Z}else if(P[D+1]==="?"){let Z=O(P,D,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let q=new S(Z.tagName);q.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(q[":@"]=this.buildAttributesMap(Z.tagExp,_,Z.tagName)),this.addChild(L,q,_)}D=Z.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let Z=b(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let q=P.substring(D+4,Z-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:q}])}D=Z}else if(P.substr(D+1,2)==="!D"){let Z=F(P,D);this.docTypeEntities=Z.entities,D=Z.i}else if(P.substr(D+1,2)==="!["){let Z=b(P,"]]>",D,"CDATA is not closed.")-2,q=P.substring(D+9,Z);B=this.saveTextToParentTag(B,L,_);let pe=this.parseTextData(q,L.tagname,_,!0,!1,!0,!0);pe==null&&(pe=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:q}]):L.add(this.options.textNodeName,pe),D=Z+2}else{let Z=O(P,D,this.options.removeNSPrefix),q=Z.tagName,pe=Z.rawTagName,oe=Z.tagExp,Se=Z.attrExpPresent,Li=Z.closeIndex;this.options.transformTagName&&(q=this.options.transformTagName(q)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let _i=L;if(_i&&this.options.unpairedTags.indexOf(_i.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),q!==T.tagname&&(_+=_?"."+q:q),this.isItStopNode(this.options.stopNodes,_,q)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=Z.closeIndex;else if(this.options.unpairedTags.indexOf(q)!==-1)D=Z.closeIndex;else{let Jn=this.readStopNodeData(P,pe,Li+1);if(!Jn)throw new Error(`Unexpected end of ${pe}`);D=Jn.i,Oe=Jn.tagContent}let Wn=new S(q);q!==oe&&Se&&(Wn[":@"]=this.buildAttributesMap(oe,_,q)),Oe&&(Oe=this.parseTextData(Oe,q,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),Wn.add(this.options.textNodeName,Oe),this.addChild(L,Wn,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){q[q.length-1]==="/"?(q=q.substr(0,q.length-1),_=_.substr(0,_.length-1),oe=q):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(q=this.options.transformTagName(q));let Oe=new S(q);q!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,q)),this.addChild(L,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new S(q);this.tagsNodeStack.push(L),q!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,q)),this.addChild(L,Oe,_),L=Oe}B="",D=Li}}else B+=P[D];return T.child},"parseXml");function M(P,T,L){let B=this.options.updateTag(T.tagname,L,T[":@"]);B===!1||(typeof B=="string"&&(T.tagname=B),P.addChild(T))}i(M,"addChild"),r(M,"addChild");var le=r(function(P){if(this.options.processEntities){for(let T in this.docTypeEntities){let L=this.docTypeEntities[T];P=P.replace(L.regx,L.val)}for(let T in this.lastEntities){let L=this.lastEntities[T];P=P.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let L=this.htmlEntities[T];P=P.replace(L.regex,L.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function J(P,T,L,B){return P&&(B===void 0&&(B=Object.keys(T.child).length===0),P=this.parseTextData(P,T.tagname,L,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&T.add(this.options.textNodeName,P),P=""),P}i(J,"saveTextToParentTag"),r(J,"saveTextToParentTag");function X(P,T,L){let B="*."+L;for(let _ in P){let D=P[_];if(B===D||T===D)return!0}return!1}i(X,"isItStopNode"),r(X,"isItStopNode");function Ce(P,T,L=">"){let B,_="";for(let D=T;D<P.length;D++){let ee=P[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===L[0])if(L[1]){if(P[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),r(Ce,"tagExpWithClosingIndex");function b(P,T,L,B){let _=P.indexOf(T,L);if(_===-1)throw new Error(B);return _+T.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(P,T,L,B=">"){let _=Ce(P,T+1,B);if(!_)return;let D=_.data,ee=_.index,Z=D.search(/\s/),q=D,pe=!0;Z!==-1&&(q=D.substring(0,Z),D=D.substring(Z+1).trimStart());let oe=q;if(L){let Se=q.indexOf(":");Se!==-1&&(q=q.substr(Se+1),pe=q!==_.data.substr(Se+1))}return{tagName:q,tagExp:D,closeIndex:ee,attrExpPresent:pe,rawTagName:oe}}i(O,"readTagExp"),r(O,"readTagExp");function G(P,T,L){let B=L,_=1;for(;L<P.length;L++)if(P[L]==="<")if(P[L+1]==="/"){let D=b(P,">",L,`${T} is not closed`);if(P.substring(L+2,D).trim()===T&&(_--,_===0))return{tagContent:P.substring(B,L),i:D};L=D}else if(P[L+1]==="?")L=b(P,"?>",L+1,"StopNode is not closed.");else if(P.substr(L+1,3)==="!--")L=b(P,"-->",L+3,"StopNode is not closed.");else if(P.substr(L+1,2)==="![")L=b(P,"]]>",L,"StopNode is not closed.")-2;else{let D=O(P,L,">");D&&((D&&D.tagName)===T&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function me(P,T,L){if(T&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:z(P,L)}else return N.isExist(P)?P:""}i(me,"parseValue"),r(me,"parseValue"),A.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function A($,C){return N($,C)}i(A,"prettify"),r(A,"prettify");function N($,C,U){let V,j={};for(let x=0;x<$.length;x++){let I=$[x],M=S(I),le="";if(U===void 0?le=M:le=U+"."+M,M===C.textNodeName)V===void 0?V=I[M]:V+=""+I[M];else{if(M===void 0)continue;if(I[M]){let J=N(I[M],C,le),X=z(J,C);I[":@"]?F(J,I[":@"],le,C):Object.keys(J).length===1&&J[C.textNodeName]!==void 0&&!C.alwaysCreateTextNode?J=J[C.textNodeName]:Object.keys(J).length===0&&(C.alwaysCreateTextNode?J[C.textNodeName]="":J=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(J)):C.isArray(M,le,X)?j[M]=[J]:j[M]=J}}}return typeof V=="string"?V.length>0&&(j[C.textNodeName]=V):V!==void 0&&(j[C.textNodeName]=V),j}i(N,"compress"),r(N,"compress");function S($){let C=Object.keys($);for(let U=0;U<C.length;U++){let V=C[U];if(V!==":@")return V}}i(S,"propName"),r(S,"propName");function F($,C,U,V){if(C){let j=Object.keys(C),x=j.length;for(let I=0;I<x;I++){let M=j[I];V.isArray(M,U+"."+M,!0,!0)?$[M]=[C[M]]:$[M]=C[M]}}}i(F,"assignAttributes"),r(F,"assignAttributes");function z($,C){let{textNodeName:U}=C,V=Object.keys($).length;return!!(V===0||V===1&&($[U]||typeof $[U]=="boolean"||$[U]===0))}i(z,"isLeafTag"),r(z,"isLeafTag"),R.prettify=A}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var A=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},N,O);let G=[],me=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let T=0;T<b.length;T++)if(b[T]==="<"&&b[T+1]==="?"){if(T+=2,T=F(b,T),T.err)return T}else if(b[T]==="<"){let L=T;if(T++,b[T]==="!"){T=z(b,T);continue}else{let B=!1;b[T]==="/"&&(B=!0,T++);let _="";for(;T<b.length&&b[T]!==">"&&b[T]!==" "&&b[T]!==" "&&b[T]!==`
83
+ `&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let Z;return _.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+_+"' is an invalid name.",M("InvalidTag",Z,X(b,T))}let D=U(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 Z=T-ee.length;ee=ee.substring(0,ee.length-1);let q=j(ee,O);if(q===!0)me=!0;else return M(q.err.code,q.err.msg,X(b,Z+q.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 Z=G.pop();if(_!==Z.tagName){let q=X(b,Z.tagStartPos);return M("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(P=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let Z=j(ee,O);if(Z!==!0)return M(Z.err.code,Z.err.msg,X(b,T-ee.length+Z.err.line));if(P===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let Z=I(b,T);if(Z==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=Z}else if(P===!0&&!S(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(S(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(b){return b===" "||b===" "||b===`
84
+ `||b==="\r"}i(S,"isWhiteSpace"),r(S,"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"),r(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"),r(z,"readCommentAndCDATA");var $='"',C="'";function U(b,O){let G="",me="",P=!1;for(;O<b.length;O++){if(b[O]===$||b[O]===C)me===""?me=b[O]:me!==b[O]||(me="");else if(b[O]===">"&&me===""){P=!0;break}G+=b[O]}return me!==""?!1:{value:G,index:O,tagClosed:P}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(b,O){let G=A.getAllMatches(b,V),me={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return M("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Ce(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return M("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Ce(G[P]));if(G[P][3]===void 0&&!O.allowBooleanAttributes)return M("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Ce(G[P]));let T=G[P][2];if(!le(T))return M("InvalidAttr","Attribute '"+T+"' is an invalid name.",Ce(G[P]));if(!me.hasOwnProperty(T))me[T]=1;else return M("InvalidAttr","Attribute '"+T+"' is repeated.",Ce(G[P]))}return!0}i(j,"validateAttributeString"),r(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"),r(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"),r(I,"validateAmpersand");function M(b,O,G){return{err:{code:b,msg:O,line:G.line||G,col:G.col}}}i(M,"getErrorObject"),r(M,"getErrorObject");function le(b){return A.isName(b)}i(le,"validateAttrName"),r(le,"validateAttrName");function J(b){return A.isName(b)}i(J,"validateTagName"),r(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"),r(X,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),r(Ce,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,A){var{buildOptions:N}=s(),S=d(),{prettify:F}=p(),z=f(),$=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(C){this.externalEntities={},this.options=N(C)}parse(C,U){if(typeof C!="string")if(C.toString)C=C.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let x=z.validate(C,U);if(x!==!0)throw Error(`${x.err.msg}:${x.err.line}:${x.err.col}`)}let V=new S(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(C);return this.options.preserveOrder||j===void 0?j:F(j,this.options)}addEntity(C,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(C.indexOf("&")!==-1||C.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[C]=U}};A.exports=$}});let v=y();return new v(n)},"getXmlParser");var Ii=class extends Je{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?Ve(e.parseOnStatusCodes):void 0,this.parser=uu({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ei=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 nn=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),Ke().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var cu=10,lu=3e4,rn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=lu,this.#r=cu}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:lu,this.#r=cu}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 sp(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Ke().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new m(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function sp(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new m(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(sp,"waitUntilTrue");var xi,qe=class{static{i(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new nn(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{xi=r;let o=Date.now();return r.addResponseSendingFinalHook(async s=>{let a={deploymentName:h.instance.deploymentName??"",instanceId:h.instance.instanceId,systemUserAgent:h.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},u=await this.#e.generateLogEntry(s,t,r,a);this.#n.enqueue(u)}),t})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){ap(t,this.#e.name)}},"#dispatch");#n};function ap(n,e){if(!xi){let r=Ke(),o=ne({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,xi.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}i(ap,"logError");var du="plugin.azure-blob-request-logger",up=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${h.instance.instanceId}.csv`,"defaultGenerateBlobName"),pu,vi=class extends ye{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,g(du)}async initialize(e){new qe({name:du,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t=cp(e[0]),r=dp(e,t),s=(this.#e.generateBlobName??up)(e);await pp(r,this.#e,s)},"#dispatch")};function cp(n){return Object.keys(n)}i(cp,"getHeaders");function lp(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
85
+ `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(lp,"escapeCsvValue");function dp(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let s of e){let a=r[s];o.push(lp(a))}t.push(o.join(","))}return t.join(`
86
+ `)}i(dp,"generateCsvContent");async function pp(n,e,t){let{sasUrl:r}=e,o=r.split("?"),s=`${o[0]}/${t}?${o[1]}`;try{let a=await H.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(Ti({message:a.statusText,status:a.status,details:await a.text()}),Ti({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Ti(a)}}i(pp,"uploadToAzureBlobStorage");function Ti(n){if(!pu){let t=Ke(),r=ne({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,pu.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(Ti,"logError");function Gn(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t||`Operation timed out after ${e} second(s)`))},e*1e3);n.then(a=>{clearTimeout(s),r(a)}).catch(a=>{clearTimeout(s),o(a)})})}i(Gn,"withTimeout");async function mp(n,e,t,r){let o;for(let s=0;s<t;s++)try{let a=fetch(n,e),u=r?await Gn(a,r,"Fetch timed out"):await a;if(u.ok)return u;o=new Error(`Fetch returned status ${u.status}`)}catch(a){o=a}throw o||new Error("Fetch failed without a response.")}i(mp,"fetchWithRetry");async function gp(n,e,t,r,o){let s;for(let a=0;a<r;a++)try{let u=new Headers(e.headers||{});u.set("Authorization",`Bearer ${t}`);let c={...e,headers:u},l=fetch(n,c),d=o?await Gn(l,o,"Fetch timed out"):await l;if(d.status===401||d.ok)return d;s=new Error(`Fetch returned status ${d.status}`)}catch(u){s=u}throw s||new Error("Fetch with token failed without a response.")}i(gp,"fetchWithToken");async function on(n,e={}){let{retries:t=3,timeoutSeconds:r,auth:o,...s}=e;if(!o)return await mp(n,s,t,r);let a=o.retries??3,u=o.timeoutSeconds,c;for(let l=0;l<a;l++)try{let d=o.callback();if(c=u?await Gn(d,u,"Auth token acquisition timed out"):await d,c)break}catch(d){if(l===a-1)throw d}if(!c)throw new Error("Failed to acquire token after maximum retries.");for(let l=0;l<a;l++){let d=await gp(n,s,c,t,r);if(d.status!==401)return d;for(let p=0;p<a;p++)try{let f=o.callback();if(c=u?await Gn(f,u,"Auth token acquisition timed out"):await f,c)break}catch(f){if(p===a-1)throw f}if(!c)throw new Error("Failed to refresh token after receiving a 401.")}throw new Error("Authentication failed after maximum token retries.")}i(on,"supafetch");function mu(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}i(mu,"decodeJWT");function gu(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let s=e.headers.get(r);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${r}/RAW/${s}`};if(o.JWT){let a=s;if(r.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=mu(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${r}/JWT/${c}/${u[c]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,s]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=mu(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i(gu,"checkRequest");var fp="unused",sn={index:1,type:15,version:"3.2.3"},hu="REQUEST_CLONE_fc64713a-d8e9-44bf-b7a2-2edffd0db542";function hp(n){let e=te.get(n,hu);if(!e)throw new Error("AkamaiApiSecurityPlugin: Fatal error - no request clone on ContextData");return e}i(hp,"getRequestClone");function yp(n,e){te.set(n,hu,e)}i(yp,"setRequestClone");var fu="plugin.akamai-api-security-plugin",Ci=class extends ye{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#n=e,g(fu)}async initialize(e){e.addRequestHook(async(t,r)=>{let o=t.clone();if(yp(r,o),this.#n.enableProtection===!0)try{let s=await this.#t.get(fp),a=gu(s,t);if(a.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${a.source}':'${a.id}'`),E.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(s){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${s.message}'`)}return t}),new qe({name:fu,generateLogEntry:this.#r,batchPeriodSeconds:this.#n.batchPeriodSeconds,dispatchFunction:this.#o},e)}#e=i(async()=>{let e=await on(`https://${this.#n.hostname}/integrations-adapter/get-prevention-rules?source-index=${sn.index}&source-key=${this.#n.key}&source-type=${sn.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch{throw new Error(`Error parsing response from protection endpoint '${t}'`)}},"#protectionFetch");#t=new rn(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r=i(async(e,t,r,o)=>{let s=hp(r),a=e.clone(),[u,c]=await Promise.all([s.text(),a.text()]),l=new URL(t.url),d=t.headers.get("true-client-ip")??"",p=o.requestStartTime.getTime();return{ip:{v:wp(d),src:d},tcp:{dst:bp(l)},http:{request:{ts:p,method:t.method,url:l.pathname,headers:Object.fromEntries(t.headers.entries()),body:u},response:{ts:p+o.durationMs,status:e.status,headers:Object.fromEntries(e.headers.entries()),body:c}},source:{type:sn.type,index:sn.index,version:sn.version,key:this.#n.key}}},"#generateEntry");#o=i(async e=>{e.length!==0&&await on(`https://${this.#n.hostname}/engine`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),retries:1})},"#dispatch")};function bp(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}i(bp,"guessPort");function wp(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}i(wp,"detectIPVersion");var Rp=i(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),yu="plugin.hydrolix-request-logger",Oi=class extends ye{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,g(yu)}async initialize(e){new qe({name:yu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t.token=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await on(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e),retries:1})},"#dispatch")};var Pp="plugin.request-logger",Si=class extends ye{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(Pp)}async initialize(e){new qe(this.#e,e)}#e};async function Ip(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,h.instance.zuploEdgeApiUrl),s=new Headers(e.headers);_e(s),s.set("Content-Type","application/json");let a={method:t,headers:s};r&&(a.body=JSON.stringify(r));let u=await H.fetch(o,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(Ip,"apiServices");var Ai=["sha-1","sha-256","sha-384","sha-512"],Vn=class{static{i(this,"BaseCryptoBeta")}};var ki=class extends Vn{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Ai.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Ai.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};export{Co as AWSLoggingPlugin,Ci as AkamaiApiSecurityPlugin,Al as AmberfloMeteringInboundPolicy,zo as AmberfloMeteringPolicy,_l as ApiAuthKeyInboundPolicy,Bo as ApiKeyInboundPolicy,Go as AsertoAuthZInboundPolicy,Do as AuditLogDataStaxProvider,Mo as AuditLogPlugin,Ul as Auth0JwtInboundPolicy,Jc as AwsLambdaHandlerExtensions,Ko as AxiomaticsAuthZInboundPolicy,vi as AzureBlobPlugin,nn as BackgroundDispatcher,rn as BackgroundLoader,Hl as BasicAuthInboundPolicy,Ka as BasicRateLimitInboundPolicy,Y as BatchDispatch,Xo as BrownoutInboundPolicy,Kl as CachingInboundPolicy,Ql as ChangeMethodInboundPolicy,Yl as ClearHeadersInboundPolicy,Xl as ClearHeadersOutboundPolicy,ed as ClerkJwtInboundPolicy,td as CognitoJwtInboundPolicy,ii as ComplexRateLimitInboundPolicy,ld as CompositeInboundPolicy,dd as CompositeOutboundPolicy,m as ConfigurationError,kr as ContentTypes,te as ContextData,ki as CryptoBeta,pd as CurityPhantomTokenInboundPolicy,oo as DataDogLoggingPlugin,Ao as DataDogMetricsPlugin,bo as DynaTraceLoggingPlugin,_o as DynatraceMetricsPlugin,gd as FirebaseJwtInboundPolicy,fd as FormDataToJsonInboundPolicy,hd as GeoFilterInboundPolicy,Xr as GoogleCloudLoggingPlugin,uo as Handler,E as HttpProblems,yn as HttpStatusCode,Oi as HydrolixRequestLoggerPlugin,ce as InboundPolicy,yd as JWTScopeValidationInboundPolicy,Ro as LokiLoggingPlugin,yt as LookupResult,ie as MemoryZoneReadThroughCache,bd as MockApiInboundPolicy,Td as MoesifInboundPolicy,ci as MonetizationInboundPolicy,li as OktaFGAAuthZInboundPolicy,Cd as OktaJwtInboundPolicy,di as OpenFGAAuthZInboundPolicy,Re as OpenIdJwtInboundPolicy,Je as OutboundPolicy,rt as ProblemResponseFormatter,Sd as PropelAuthJwtInboundPolicy,gi as QuotaInboundPolicy,Ka as RateLimitInboundPolicy,Dd as ReadmeMetricsInboundPolicy,Md as RemoveHeadersInboundPolicy,qd as RemoveHeadersOutboundPolicy,Ud as RemoveQueryParamsInboundPolicy,Hd as ReplaceStringOutboundPolicy,Si as RequestLoggerPlugin,$d as RequestSizeLimitInboundPolicy,ou as RequestValidationInboundPolicy,Fd as RequireOriginInboundPolicy,Ht as ResponseSendingEvent,$t as ResponseSentEvent,k as RuntimeError,dn as SYSTEM_LOGGER,Zd as SchemaBasedRequestValidation,Ze as SemanticAttributes,Ei as ServiceProviderImpl,jd as SetBodyInboundPolicy,zd as SetHeadersInboundPolicy,Bd as SetHeadersOutboundPolicy,Gd as SetQueryParamsInboundPolicy,Vd as SetStatusOutboundPolicy,Jd as SleepInboundPolicy,Ia as StripeMonetizationPlugin,Yt as StripeWebhookVerificationInboundPolicy,Eo as SumoLogicLoggingPlugin,Kd as SupabaseJwtInboundPolicy,Ue as SystemRouteName,qt as TelemetryPlugin,Qd as UpstreamAzureAdServiceAuthInboundPolicy,Xd as UpstreamFirebaseAdminAuthInboundPolicy,np as UpstreamFirebaseUserAuthInboundPolicy,wi as UpstreamGcpFederatedAuthInboundPolicy,rp as UpstreamGcpJwtInboundPolicy,op as UpstreamGcpServiceAuthInboundPolicy,To as VMWareLogInsightLoggingPlugin,ip as ValidateJsonSchemaInbound,Ii as XmlToJsonOutboundPolicy,Nt as ZoneCache,re as ZuploRequest,tn as ZuploServices,Ip as apiServices,Kc as awsLambdaHandler,Rp as defaultGenerateHydrolixEntry,Pe as environment,Kn as getIdForParameterSchema,Pu as getIdForRefSchema,Qn as getIdForRequestBodySchema,Ru as getRawOperationDataIdentifierName,Nr as httpStatuses,ol as openApiSpecHandler,sl as redirectHandler,Iu as sanitizedIdentifierName,Lr as serialize,Id as setMoesifContext,g as trackFeature,cl as urlForwardHandler,dl as urlRewriteHandler,pl as webSocketHandler,ml as webSocketPipelineHandler,al as zuploServiceProxy};
87
87
  /*! For license information please see index.js.LEGAL.txt */