@zuplo/runtime 5.1954.0 → 5.1958.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.min.js CHANGED
@@ -23,23 +23,23 @@
23
23
  * DEALINGS IN THE SOFTWARE.
24
24
  *--------------------------------------------------------------------------------------------*/
25
25
 
26
- var Oa=Object.create;var Ln=Object.defineProperty;var Ca=Object.getOwnPropertyDescriptor;var Aa=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,_a=Object.prototype.hasOwnProperty;var i=(t,e)=>Ln(t,"name",{value:e,configurable:!0});var Ve=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Na=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Aa(e))!_a.call(t,o)&&o!==n&&Ln(t,o,{get:()=>e[o],enumerable:!(r=Ca(e,o))||r.enumerable});return t};var Se=(t,e,n)=>(n=t!=null?Oa(La(t)):{},Na(e||!t||!t.__esModule?Ln(n,"default",{value:t,enumerable:!0}):n,t));var Ei=Ve(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var gi=!0,Wn=!gi;function ka(t){gi||(Wn=t)}i(ka,"setColorEnabled");v.setColorEnabled=ka;function Ma(){return Wn}i(Ma,"getColorEnabled");v.getColorEnabled=Ma;function U(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(U,"code");function Z(t,e){return Wn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(Z,"run");function Da(t){return Z(t,U([0],0))}i(Da,"reset");v.reset=Da;function Ha(t){return Z(t,U([1],22))}i(Ha,"bold");v.bold=Ha;function Ua(t){return Z(t,U([2],22))}i(Ua,"dim");v.dim=Ua;function Za(t){return Z(t,U([3],23))}i(Za,"italic");v.italic=Za;function qa(t){return Z(t,U([4],24))}i(qa,"underline");v.underline=qa;function $a(t){return Z(t,U([7],27))}i($a,"inverse");v.inverse=$a;function Fa(t){return Z(t,U([8],28))}i(Fa,"hidden");v.hidden=Fa;function Ba(t){return Z(t,U([9],29))}i(Ba,"strikethrough");v.strikethrough=Ba;function za(t){return Z(t,U([30],39))}i(za,"black");v.black=za;function fi(t){return Z(t,U([31],39))}i(fi,"red");v.red=fi;function hi(t){return Z(t,U([32],39))}i(hi,"green");v.green=hi;function yi(t){return Z(t,U([33],39))}i(yi,"yellow");v.yellow=yi;function bi(t){return Z(t,U([34],39))}i(bi,"blue");v.blue=bi;function wi(t){return Z(t,U([35],39))}i(wi,"magenta");v.magenta=wi;function Ri(t){return Z(t,U([36],39))}i(Ri,"cyan");v.cyan=Ri;function ja(t){return Z(t,U([37],39))}i(ja,"white");v.white=ja;function Va(t){return Pi(t)}i(Va,"gray");v.gray=Va;function Pi(t){return Z(t,U([90],39))}i(Pi,"brightBlack");v.brightBlack=Pi;function Ga(t){return Z(t,U([91],39))}i(Ga,"brightRed");v.brightRed=Ga;function Wa(t){return Z(t,U([92],39))}i(Wa,"brightGreen");v.brightGreen=Wa;function Ka(t){return Z(t,U([93],39))}i(Ka,"brightYellow");v.brightYellow=Ka;function Ja(t){return Z(t,U([94],39))}i(Ja,"brightBlue");v.brightBlue=Ja;function Ya(t){return Z(t,U([95],39))}i(Ya,"brightMagenta");v.brightMagenta=Ya;function Qa(t){return Z(t,U([96],39))}i(Qa,"brightCyan");v.brightCyan=Qa;function Xa(t){return Z(t,U([97],39))}i(Xa,"brightWhite");v.brightWhite=Xa;function eu(t){return Z(t,U([40],49))}i(eu,"bgBlack");v.bgBlack=eu;function tu(t){return Z(t,U([41],49))}i(tu,"bgRed");v.bgRed=tu;function nu(t){return Z(t,U([42],49))}i(nu,"bgGreen");v.bgGreen=nu;function ru(t){return Z(t,U([43],49))}i(ru,"bgYellow");v.bgYellow=ru;function ou(t){return Z(t,U([44],49))}i(ou,"bgBlue");v.bgBlue=ou;function iu(t){return Z(t,U([45],49))}i(iu,"bgMagenta");v.bgMagenta=iu;function su(t){return Z(t,U([46],49))}i(su,"bgCyan");v.bgCyan=su;function au(t){return Z(t,U([47],49))}i(au,"bgWhite");v.bgWhite=au;function uu(t){return Z(t,U([100],49))}i(uu,"bgBrightBlack");v.bgBrightBlack=uu;function cu(t){return Z(t,U([101],49))}i(cu,"bgBrightRed");v.bgBrightRed=cu;function lu(t){return Z(t,U([102],49))}i(lu,"bgBrightGreen");v.bgBrightGreen=lu;function du(t){return Z(t,U([103],49))}i(du,"bgBrightYellow");v.bgBrightYellow=du;function pu(t){return Z(t,U([104],49))}i(pu,"bgBrightBlue");v.bgBrightBlue=pu;function mu(t){return Z(t,U([105],49))}i(mu,"bgBrightMagenta");v.bgBrightMagenta=mu;function gu(t){return Z(t,U([106],49))}i(gu,"bgBrightCyan");v.bgBrightCyan=gu;function fu(t){return Z(t,U([107],49))}i(fu,"bgBrightWhite");v.bgBrightWhite=fu;function Oe(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}i(Oe,"clampAndTruncate");function hu(t,e){return Z(t,U([38,5,Oe(e)],39))}i(hu,"rgb8");v.rgb8=hu;function yu(t,e){return Z(t,U([48,5,Oe(e)],49))}i(yu,"bgRgb8");v.bgRgb8=yu;function bu(t,e){return typeof e=="number"?Z(t,U([38,2,e>>16&255,e>>8&255,e&255],39)):Z(t,U([38,2,Oe(e.r),Oe(e.g),Oe(e.b)],39))}i(bu,"rgb24");v.rgb24=bu;function wu(t,e){return typeof e=="number"?Z(t,U([48,2,e>>16&255,e>>8&255,e&255],49)):Z(t,U([48,2,Oe(e.r),Oe(e.g),Oe(e.b)],49))}i(wu,"bgRgb24");v.bgRgb24=wu;var Ru=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");function Pu(t){return t.replace(Ru,"")}i(Pu,"stripColor");v.stripColor=Pu;v.colorFunctions=[fi,hi,yi,bi,wi,Ri];function Eu(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}i(Eu,"hashCode");function Iu(t){let e=Math.abs(Eu(t));return v.colorFunctions[e%v.colorFunctions.length]}i(Iu,"generateColor");v.generateColor=Iu});var Ii=Ve(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.format=void 0;function xu(t,e,...n){let r=0,o=n.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
27
- `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}i(xu,"format");Mt.format=xu});var Ci=Ve(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.inspect=void 0;function Ue(t,e,n,r){let o={seen:[],stylize:vu,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Su),Dt(o,t,o.depth)}i(Ue,"inspect");Ht.inspect=Ue;Ue.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]};Ue.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function vu(t,e){return t}i(vu,"stylizeNoColor");function Tu(t){return typeof t=="boolean"}i(Tu,"isBoolean");function vi(t){return t===void 0}i(vi,"isUndefined");function Su(t,e){let n=Ue.styles[e];return n?"\x1B["+Ue.colors[n][0]+"m"+t+"\x1B["+Ue.colors[n][1]+"m":t}i(Su,"stylizeWithColor");function Kn(t){return typeof t=="function"}i(Kn,"isFunction");function Ti(t){return typeof t=="string"}i(Ti,"isString");function Ou(t){return typeof t=="number"}i(Ou,"isNumber");function Si(t){return t===null}i(Si,"isNull");function Oi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(Oi,"hasOwn");function Jn(t){return er(t)&&tr(t)==="[object RegExp]"}i(Jn,"isRegExp");function er(t){return typeof t=="object"&&t!==null}i(er,"isObject");function Yn(t){return er(t)&&(tr(t)==="[object Error]"||t instanceof Error)}i(Yn,"isError");function xi(t){return er(t)&&tr(t)==="[object Date]"}i(xi,"isDate");function tr(t){return Object.prototype.toString.call(t)}i(tr,"objectToString");function Cu(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}i(Cu,"arrayToHash");function Au(t,e,n,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Oi(e,String(a))?s.push(Xn(t,e,n,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Xn(t,e,n,r,a,!0))}),s}i(Au,"formatArray");function Qn(t){return"["+Error.prototype.toString.call(t)+"]"}i(Qn,"formatError");function Dt(t,e,n){if(t.customInspect&&e&&Kn(e.inspect)&&e.inspect!==Ue&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return Ti(d)||(d=Dt(t,d,n)),d}let r=Lu(t,e);if(r)return r;let o=Object.keys(e),s=Cu(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Yn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Qn(e);if(o.length===0){if(Kn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Jn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(xi(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Yn(e))return Qn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Kn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Jn(e)&&(a=" "+RegExp.prototype.toString.call(e)),xi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Yn(e)&&(a=" "+Qn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Jn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Au(t,e,n,s,o):l=o.map(function(d){return Xn(t,e,n,s,d,u)}),t.seen.pop(),_u(l,a,c)}i(Dt,"formatValue");function Xn(t,e,n,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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),Oi(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Si(n)?u=Dt(t,c.value,null):u=Dt(t,c.value,n-1),u.indexOf(`
26
+ var Aa=Object.create;var Ln=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var La=Object.getOwnPropertyNames;var Na=Object.getPrototypeOf,ka=Object.prototype.hasOwnProperty;var i=(t,e)=>Ln(t,"name",{value:e,configurable:!0});var Ge=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ma=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of La(e))!ka.call(t,o)&&o!==n&&Ln(t,o,{get:()=>e[o],enumerable:!(r=_a(e,o))||r.enumerable});return t};var Se=(t,e,n)=>(n=t!=null?Aa(Na(t)):{},Ma(e||!t||!t.__esModule?Ln(n,"default",{value:t,enumerable:!0}):n,t));var vi=Ge(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.generateColor=x.colorFunctions=x.stripColor=x.bgRgb24=x.rgb24=x.bgRgb8=x.rgb8=x.bgBrightWhite=x.bgBrightCyan=x.bgBrightMagenta=x.bgBrightBlue=x.bgBrightYellow=x.bgBrightGreen=x.bgBrightRed=x.bgBrightBlack=x.bgWhite=x.bgCyan=x.bgMagenta=x.bgBlue=x.bgYellow=x.bgGreen=x.bgRed=x.bgBlack=x.brightWhite=x.brightCyan=x.brightMagenta=x.brightBlue=x.brightYellow=x.brightGreen=x.brightRed=x.brightBlack=x.gray=x.white=x.cyan=x.magenta=x.blue=x.yellow=x.green=x.red=x.black=x.strikethrough=x.hidden=x.inverse=x.underline=x.italic=x.dim=x.bold=x.reset=x.getColorEnabled=x.setColorEnabled=void 0;var bi=!0,Kn=!bi;function Da(t){bi||(Kn=t)}i(Da,"setColorEnabled");x.setColorEnabled=Da;function Ha(){return Kn}i(Ha,"getColorEnabled");x.getColorEnabled=Ha;function U(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(U,"code");function Z(t,e){return Kn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}i(Z,"run");function Ua(t){return Z(t,U([0],0))}i(Ua,"reset");x.reset=Ua;function Za(t){return Z(t,U([1],22))}i(Za,"bold");x.bold=Za;function qa(t){return Z(t,U([2],22))}i(qa,"dim");x.dim=qa;function $a(t){return Z(t,U([3],23))}i($a,"italic");x.italic=$a;function Fa(t){return Z(t,U([4],24))}i(Fa,"underline");x.underline=Fa;function Ba(t){return Z(t,U([7],27))}i(Ba,"inverse");x.inverse=Ba;function za(t){return Z(t,U([8],28))}i(za,"hidden");x.hidden=za;function ja(t){return Z(t,U([9],29))}i(ja,"strikethrough");x.strikethrough=ja;function Va(t){return Z(t,U([30],39))}i(Va,"black");x.black=Va;function wi(t){return Z(t,U([31],39))}i(wi,"red");x.red=wi;function Ri(t){return Z(t,U([32],39))}i(Ri,"green");x.green=Ri;function Pi(t){return Z(t,U([33],39))}i(Pi,"yellow");x.yellow=Pi;function Ei(t){return Z(t,U([34],39))}i(Ei,"blue");x.blue=Ei;function Ii(t){return Z(t,U([35],39))}i(Ii,"magenta");x.magenta=Ii;function Ti(t){return Z(t,U([36],39))}i(Ti,"cyan");x.cyan=Ti;function Ga(t){return Z(t,U([37],39))}i(Ga,"white");x.white=Ga;function Wa(t){return xi(t)}i(Wa,"gray");x.gray=Wa;function xi(t){return Z(t,U([90],39))}i(xi,"brightBlack");x.brightBlack=xi;function Ja(t){return Z(t,U([91],39))}i(Ja,"brightRed");x.brightRed=Ja;function Ka(t){return Z(t,U([92],39))}i(Ka,"brightGreen");x.brightGreen=Ka;function Ya(t){return Z(t,U([93],39))}i(Ya,"brightYellow");x.brightYellow=Ya;function Qa(t){return Z(t,U([94],39))}i(Qa,"brightBlue");x.brightBlue=Qa;function Xa(t){return Z(t,U([95],39))}i(Xa,"brightMagenta");x.brightMagenta=Xa;function eu(t){return Z(t,U([96],39))}i(eu,"brightCyan");x.brightCyan=eu;function tu(t){return Z(t,U([97],39))}i(tu,"brightWhite");x.brightWhite=tu;function nu(t){return Z(t,U([40],49))}i(nu,"bgBlack");x.bgBlack=nu;function ru(t){return Z(t,U([41],49))}i(ru,"bgRed");x.bgRed=ru;function ou(t){return Z(t,U([42],49))}i(ou,"bgGreen");x.bgGreen=ou;function iu(t){return Z(t,U([43],49))}i(iu,"bgYellow");x.bgYellow=iu;function su(t){return Z(t,U([44],49))}i(su,"bgBlue");x.bgBlue=su;function au(t){return Z(t,U([45],49))}i(au,"bgMagenta");x.bgMagenta=au;function uu(t){return Z(t,U([46],49))}i(uu,"bgCyan");x.bgCyan=uu;function cu(t){return Z(t,U([47],49))}i(cu,"bgWhite");x.bgWhite=cu;function lu(t){return Z(t,U([100],49))}i(lu,"bgBrightBlack");x.bgBrightBlack=lu;function du(t){return Z(t,U([101],49))}i(du,"bgBrightRed");x.bgBrightRed=du;function pu(t){return Z(t,U([102],49))}i(pu,"bgBrightGreen");x.bgBrightGreen=pu;function mu(t){return Z(t,U([103],49))}i(mu,"bgBrightYellow");x.bgBrightYellow=mu;function gu(t){return Z(t,U([104],49))}i(gu,"bgBrightBlue");x.bgBrightBlue=gu;function fu(t){return Z(t,U([105],49))}i(fu,"bgBrightMagenta");x.bgBrightMagenta=fu;function hu(t){return Z(t,U([106],49))}i(hu,"bgBrightCyan");x.bgBrightCyan=hu;function yu(t){return Z(t,U([107],49))}i(yu,"bgBrightWhite");x.bgBrightWhite=yu;function Ce(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}i(Ce,"clampAndTruncate");function bu(t,e){return Z(t,U([38,5,Ce(e)],39))}i(bu,"rgb8");x.rgb8=bu;function wu(t,e){return Z(t,U([48,5,Ce(e)],49))}i(wu,"bgRgb8");x.bgRgb8=wu;function Ru(t,e){return typeof e=="number"?Z(t,U([38,2,e>>16&255,e>>8&255,e&255],39)):Z(t,U([38,2,Ce(e.r),Ce(e.g),Ce(e.b)],39))}i(Ru,"rgb24");x.rgb24=Ru;function Pu(t,e){return typeof e=="number"?Z(t,U([48,2,e>>16&255,e>>8&255,e&255],49)):Z(t,U([48,2,Ce(e.r),Ce(e.g),Ce(e.b)],49))}i(Pu,"bgRgb24");x.bgRgb24=Pu;var Eu=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");function Iu(t){return t.replace(Eu,"")}i(Iu,"stripColor");x.stripColor=Iu;x.colorFunctions=[wi,Ri,Pi,Ei,Ii,Ti];function Tu(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}i(Tu,"hashCode");function xu(t){let e=Math.abs(Tu(t));return x.colorFunctions[e%x.colorFunctions.length]}i(xu,"generateColor");x.generateColor=xu});var Oi=Ge(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.format=void 0;function vu(t,e,...n){let r=0,o=n.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
27
+ `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}i(vu,"format");Dt.format=vu});var Ni=Ge(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.inspect=void 0;function Ze(t,e,n,r){let o={seen:[],stylize:Ou,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Cu),Ht(o,t,o.depth)}i(Ze,"inspect");Ut.inspect=Ze;Ze.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]};Ze.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Ou(t,e){return t}i(Ou,"stylizeNoColor");function Su(t){return typeof t=="boolean"}i(Su,"isBoolean");function Ci(t){return t===void 0}i(Ci,"isUndefined");function Cu(t,e){let n=Ze.styles[e];return n?"\x1B["+Ze.colors[n][0]+"m"+t+"\x1B["+Ze.colors[n][1]+"m":t}i(Cu,"stylizeWithColor");function Yn(t){return typeof t=="function"}i(Yn,"isFunction");function Ai(t){return typeof t=="string"}i(Ai,"isString");function Au(t){return typeof t=="number"}i(Au,"isNumber");function _i(t){return t===null}i(_i,"isNull");function Li(t,e){return Object.prototype.hasOwnProperty.call(t,e)}i(Li,"hasOwn");function Qn(t){return nr(t)&&rr(t)==="[object RegExp]"}i(Qn,"isRegExp");function nr(t){return typeof t=="object"&&t!==null}i(nr,"isObject");function Xn(t){return nr(t)&&(rr(t)==="[object Error]"||t instanceof Error)}i(Xn,"isError");function Si(t){return nr(t)&&rr(t)==="[object Date]"}i(Si,"isDate");function rr(t){return Object.prototype.toString.call(t)}i(rr,"objectToString");function _u(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}i(_u,"arrayToHash");function Lu(t,e,n,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Li(e,String(a))?s.push(tr(t,e,n,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(tr(t,e,n,r,a,!0))}),s}i(Lu,"formatArray");function er(t){return"["+Error.prototype.toString.call(t)+"]"}i(er,"formatError");function Ht(t,e,n){if(t.customInspect&&e&&Yn(e.inspect)&&e.inspect!==Ze&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return Ai(d)||(d=Ht(t,d,n)),d}let r=Nu(t,e);if(r)return r;let o=Object.keys(e),s=_u(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Xn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return er(e);if(o.length===0){if(Yn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Qn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Si(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Xn(e))return er(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Yn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Qn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Si(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Xn(e)&&(a=" "+er(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Qn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Lu(t,e,n,s,o):l=o.map(function(d){return tr(t,e,n,s,d,u)}),t.seen.pop(),ku(l,a,c)}i(Ht,"formatValue");function tr(t,e,n,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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),Li(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(_i(n)?u=Ht(t,c.value,null):u=Ht(t,c.value,n-1),u.indexOf(`
28
28
  `)>-1&&(s?u=u.split(`
29
29
  `).map(function(l){return" "+l}).join(`
30
30
  `).substr(2):u=`
31
31
  `+u.split(`
32
32
  `).map(function(l){return" "+l}).join(`
33
- `))):u=t.stylize("[Circular]","special")),vi(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=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(Xn,"formatProperty");function Lu(t,e){if(vi(e))return t.stylize("undefined","undefined");if(Ti(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Ou(e))return t.stylize(""+e,"number");if(Tu(e))return t.stylize(""+e,"boolean");if(Si(e))return t.stylize("null","null")}i(Lu,"formatPrimitive");function _u(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
33
+ `))):u=t.stylize("[Circular]","special")),Ci(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=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(tr,"formatProperty");function Nu(t,e){if(Ci(e))return t.stylize("undefined","undefined");if(Ai(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Au(e))return t.stylize(""+e,"number");if(Su(e))return t.stylize(""+e,"boolean");if(_i(e))return t.stylize("null","null")}i(Nu,"formatPrimitive");function ku(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
34
34
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
35
35
  `)+" "+t.join(`,
36
- `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(_u,"reduceToSingleString")});var Ai=Ve(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.format=void 0;var Nu=Ii(),ku=Ci(),Mu=i((t,...e)=>(0,Nu.format)(ku.inspect,t,e),"format");Ut.format=Mu});var Ae=Ve(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.debug=Ce.withoutEnv=Ce.Debugger=void 0;var Du=Ei(),Hu=Ai(),Zt=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Du.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,Hu.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ce.Debugger=Zt;var qt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Li(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Li,"extract");var at;function Uu(t){t||(t=[]),typeof t=="string"&&(t=Li(t)),at=new qt(t)}i(Uu,"withoutEnv");Ce.withoutEnv=Uu;function Zu(t){let e=globalThis.DEBUG;at||(at=new qt(Li(e)));let n=new Zt(at,t);return at.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(Zu,"debug");Ce.debug=Zu});var Ta=Ve((lS,va)=>{"use strict";var $d=Object.defineProperty,Fd=Object.getOwnPropertyNames,D=i((t,e)=>$d(t,"name",{value:e,configurable:!0}),"__name"),be=i((t,e)=>i(function(){return e||(0,t[Fd(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Zo=be({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":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=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",o=new RegExp("^"+r+"$"),s=D(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=D(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),xa=be({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Zo(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,P){P=Object.assign({},n,P);let O=[],H=!1,h=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let R=0;R<f.length;R++)if(f[R]==="<"&&f[R+1]==="?"){if(R+=2,R=o(f,R),R.err)return R}else if(f[R]==="<"){let S=R;if(R++,f[R]==="!"){R=s(f,R);continue}else{let M=!1;f[R]==="/"&&(M=!0,R++);let C="";for(;R<f.length&&f[R]!==">"&&f[R]!==" "&&f[R]!==" "&&f[R]!==`
37
- `&&f[R]!=="\r";R++)C+=f[R];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),R--),!b(C)){let k;return C.trim().length===0?k="Invalid space after '<'.":k="Tag '"+C+"' is an invalid name.",g("InvalidTag",k,x(f,R))}let _=c(f,R);if(_===!1)return g("InvalidAttr","Attributes for '"+C+"' have open quote.",x(f,R));let F=_.value;if(R=_.index,F[F.length-1]==="/"){let k=R-F.length;F=F.substring(0,F.length-1);let N=d(F,P);if(N===!0)H=!0;else return g(N.err.code,N.err.msg,x(f,k+N.err.line))}else if(M)if(_.tagClosed){if(F.trim().length>0)return g("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",x(f,S));{let k=O.pop();if(C!==k.tagName){let N=x(f,k.tagStartPos);return g("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+C+"'.",x(f,S))}O.length==0&&(h=!0)}}else return g("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",x(f,R));else{let k=d(F,P);if(k!==!0)return g(k.err.code,k.err.msg,x(f,R-F.length+k.err.line));if(h===!0)return g("InvalidXml","Multiple possible root nodes found.",x(f,R));P.unpairedTags.indexOf(C)!==-1||O.push({tagName:C,tagStartPos:S}),H=!0}for(R++;R<f.length;R++)if(f[R]==="<")if(f[R+1]==="!"){R++,R=s(f,R);continue}else if(f[R+1]==="?"){if(R=o(f,++R),R.err)return R}else break;else if(f[R]==="&"){let k=m(f,R);if(k==-1)return g("InvalidChar","char '&' is not expected.",x(f,R));R=k}else if(h===!0&&!r(f[R]))return g("InvalidXml","Extra text at the end",x(f,R));f[R]==="<"&&R--}}else{if(r(f[R]))continue;return g("InvalidChar","char '"+f[R]+"' is not expected.",x(f,R))}if(H){if(O.length==1)return g("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",x(f,O[0].tagStartPos));if(O.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(O.map(R=>R.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return g("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
38
- `||f==="\r"}i(r,"isWhiteSpace"),D(r,"isWhiteSpace");function o(f,P){let O=P;for(;P<f.length;P++)if(f[P]=="?"||f[P]==" "){let H=f.substr(O,P-O);if(P>5&&H==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",x(f,P));if(f[P]=="?"&&f[P+1]==">"){P++;break}else continue}return P}i(o,"readPI"),D(o,"readPI");function s(f,P){if(f.length>P+5&&f[P+1]==="-"&&f[P+2]==="-"){for(P+=3;P<f.length;P++)if(f[P]==="-"&&f[P+1]==="-"&&f[P+2]===">"){P+=2;break}}else if(f.length>P+8&&f[P+1]==="D"&&f[P+2]==="O"&&f[P+3]==="C"&&f[P+4]==="T"&&f[P+5]==="Y"&&f[P+6]==="P"&&f[P+7]==="E"){let O=1;for(P+=8;P<f.length;P++)if(f[P]==="<")O++;else if(f[P]===">"&&(O--,O===0))break}else if(f.length>P+9&&f[P+1]==="["&&f[P+2]==="C"&&f[P+3]==="D"&&f[P+4]==="A"&&f[P+5]==="T"&&f[P+6]==="A"&&f[P+7]==="["){for(P+=8;P<f.length;P++)if(f[P]==="]"&&f[P+1]==="]"&&f[P+2]===">"){P+=2;break}}return P}i(s,"readCommentAndCDATA"),D(s,"readCommentAndCDATA");var a='"',u="'";function c(f,P){let O="",H="",h=!1;for(;P<f.length;P++){if(f[P]===a||f[P]===u)H===""?H=f[P]:H!==f[P]||(H="");else if(f[P]===">"&&H===""){h=!0;break}O+=f[P]}return H!==""?!1:{value:O,index:P,tagClosed:h}}i(c,"readAttributeStr"),D(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(f,P){let O=e.getAllMatches(f,l),H={};for(let h=0;h<O.length;h++){if(O[h][1].length===0)return g("InvalidAttr","Attribute '"+O[h][2]+"' has no space in starting.",L(O[h]));if(O[h][3]!==void 0&&O[h][4]===void 0)return g("InvalidAttr","Attribute '"+O[h][2]+"' is without value.",L(O[h]));if(O[h][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+O[h][2]+"' is not allowed.",L(O[h]));let R=O[h][2];if(!I(R))return g("InvalidAttr","Attribute '"+R+"' is an invalid name.",L(O[h]));if(!H.hasOwnProperty(R))H[R]=1;else return g("InvalidAttr","Attribute '"+R+"' is repeated.",L(O[h]))}return!0}i(d,"validateAttributeString"),D(d,"validateAttributeString");function p(f,P){let O=/\d/;for(f[P]==="x"&&(P++,O=/[\da-fA-F]/);P<f.length;P++){if(f[P]===";")return P;if(!f[P].match(O))break}return-1}i(p,"validateNumberAmpersand"),D(p,"validateNumberAmpersand");function m(f,P){if(P++,f[P]===";")return-1;if(f[P]==="#")return P++,p(f,P);let O=0;for(;P<f.length;P++,O++)if(!(f[P].match(/\w/)&&O<20)){if(f[P]===";")break;return-1}return P}i(m,"validateAmpersand"),D(m,"validateAmpersand");function g(f,P,O){return{err:{code:f,msg:P,line:O.line||O,col:O.col}}}i(g,"getErrorObject"),D(g,"getErrorObject");function I(f){return e.isName(f)}i(I,"validateAttrName"),D(I,"validateAttrName");function b(f){return e.isName(f)}i(b,"validateTagName"),D(b,"validateTagName");function x(f,P){let O=f.substring(0,P).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}i(x,"getLineNumberForPosition"),D(x,"getLineNumberForPosition");function L(f){return f.startIndex+f[1].length}i(L,"getPositionFromMatch"),D(L,"getPositionFromMatch")}}),Bd=be({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,s){return r}},n=D(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),zd=be({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=class{static{i(this,"XmlNode")}static{D(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=n}}),jd=be({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=Zo();function r(p,m){let g={};if(p[m+3]==="O"&&p[m+4]==="C"&&p[m+5]==="T"&&p[m+6]==="Y"&&p[m+7]==="P"&&p[m+8]==="E"){m=m+9;let I=1,b=!1,x=!1,L="";for(;m<p.length;m++)if(p[m]==="<"&&!x){if(b&&a(p,m))m+=7,[entityName,val,m]=o(p,m+1),val.indexOf("&")===-1&&(g[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&u(p,m))m+=8;else if(b&&c(p,m))m+=8;else if(b&&l(p,m))m+=9;else if(s)x=!0;else throw new Error("Invalid DOCTYPE");I++,L=""}else if(p[m]===">"){if(x?p[m-1]==="-"&&p[m-2]==="-"&&(x=!1,I--):I--,I===0)break}else p[m]==="["?b=!0:L+=p[m];if(I!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}i(r,"readDocType"),D(r,"readDocType");function o(p,m){let g="";for(;m<p.length&&p[m]!=="'"&&p[m]!=='"';m++)g+=p[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let I=p[m++],b="";for(;m<p.length&&p[m]!==I;m++)b+=p[m];return[g,b,m]}i(o,"readEntityExp"),D(o,"readEntityExp");function s(p,m){return p[m+1]==="!"&&p[m+2]==="-"&&p[m+3]==="-"}i(s,"isComment"),D(s,"isComment");function a(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="N"&&p[m+4]==="T"&&p[m+5]==="I"&&p[m+6]==="T"&&p[m+7]==="Y"}i(a,"isEntity"),D(a,"isEntity");function u(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="L"&&p[m+4]==="E"&&p[m+5]==="M"&&p[m+6]==="E"&&p[m+7]==="N"&&p[m+8]==="T"}i(u,"isElement"),D(u,"isElement");function c(p,m){return p[m+1]==="!"&&p[m+2]==="A"&&p[m+3]==="T"&&p[m+4]==="T"&&p[m+5]==="L"&&p[m+6]==="I"&&p[m+7]==="S"&&p[m+8]==="T"}i(c,"isAttlist"),D(c,"isAttlist");function l(p,m){return p[m+1]==="!"&&p[m+2]==="N"&&p[m+3]==="O"&&p[m+4]==="T"&&p[m+5]==="A"&&p[m+6]==="T"&&p[m+7]==="I"&&p[m+8]==="O"&&p[m+9]==="N"}i(l,"isNotation"),D(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),D(d,"validateEntityName"),e.exports=r}}),Vd=be({"../../node_modules/strnum/strnum.js"(t,e){var n=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(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 o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&n.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],m=d[2],g=a(d[3]),I=d[4]||d[6];if(!c.leadingZeros&&m.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!p&&l[1]!==".")return u;{let b=Number(l),x=""+b;return x.search(/[eE]/)!==-1||I?c.eNotation?b:u:l.indexOf(".")!==-1?x==="0"&&g===""||x===g||p&&x==="-"+g?b:u:m?g===x||p+g===x?b:u:l===x||l===p+x?b:u}}else return u}}i(s,"toNumber"),D(s,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}i(a,"trimZeros"),D(a,"trimZeros"),e.exports=s}}),Gd=be({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=Zo(),r=zd(),o=jd(),s=Vd(),a=class{static{i(this,"OrderedObjParser")}static{D(this,"OrderedObjParser")}constructor(h){this.options=h,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"}},this.addExternalEntities=u,this.parseXml=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=x,this.replaceEntitiesValue=I,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=g}};function u(h){let R=Object.keys(h);for(let S=0;S<R.length;S++){let M=R[S];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:h[M]}}}i(u,"addExternalEntities"),D(u,"addExternalEntities");function c(h,R,S,M,C,_,F){if(h!==void 0&&(this.options.trimValues&&!M&&(h=h.trim()),h.length>0)){F||(h=this.replaceEntitiesValue(h));let k=this.options.tagValueProcessor(R,h,S,C,_);return k==null?h:typeof k!=typeof h||k!==h?k:this.options.trimValues?H(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?H(h,this.options.parseTagValue,this.options.numberParseOptions):h}}i(c,"parseTextData"),D(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let R=h.split(":"),S=h.charAt(0)==="/"?"/":"";if(R[0]==="xmlns")return"";R.length===2&&(h=S+R[1])}return h}i(l,"resolveNameSpace"),D(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(h,R,S){if(!this.options.ignoreAttributes&&typeof h=="string"){let M=n.getAllMatches(h,d),C=M.length,_={};for(let F=0;F<C;F++){let k=this.resolveNameSpace(M[F][1]),N=M[F][4],W=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(W=this.options.transformAttributeName(W)),W==="__proto__"&&(W="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let j=this.options.attributeValueProcessor(k,N,R);j==null?_[W]=N:typeof j!=typeof N||j!==N?_[W]=j:_[W]=H(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[W]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let F={};return F[this.options.attributesGroupName]=_,F}return _}}i(p,"buildAttributesMap"),D(p,"buildAttributesMap");var m=D(function(h){h=h.replace(/\r\n?/g,`
39
- `);let R=new r("!xml"),S=R,M="",C="";for(let _=0;_<h.length;_++)if(h[_]==="<")if(h[_+1]==="/"){let k=f(h,">",_,"Closing Tag is not closed."),N=h.substring(_+2,k).trim();if(this.options.removeNSPrefix){let pe=N.indexOf(":");pe!==-1&&(N=N.substr(pe+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(M=this.saveTextToParentTag(M,S,C));let W=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let j=0;W&&this.options.unpairedTags.indexOf(W)!==-1?(j=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):j=C.lastIndexOf("."),C=C.substring(0,j),S=this.tagsNodeStack.pop(),M="",_=k}else if(h[_+1]==="?"){let k=P(h,_,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,S,C),!(this.options.ignoreDeclaration&&k.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(k.tagName);N.add(this.options.textNodeName,""),k.tagName!==k.tagExp&&k.attrExpPresent&&(N[":@"]=this.buildAttributesMap(k.tagExp,C,k.tagName)),this.addChild(S,N,C)}_=k.closeIndex+1}else if(h.substr(_+1,3)==="!--"){let k=f(h,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=h.substring(_+4,k-2);M=this.saveTextToParentTag(M,S,C),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=k}else if(h.substr(_+1,2)==="!D"){let k=o(h,_);this.docTypeEntities=k.entities,_=k.i}else if(h.substr(_+1,2)==="!["){let k=f(h,"]]>",_,"CDATA is not closed.")-2,N=h.substring(_+9,k);M=this.saveTextToParentTag(M,S,C);let W=this.parseTextData(N,S.tagname,C,!0,!1,!0,!0);W==null&&(W=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,W),_=k+2}else{let k=P(h,_,this.options.removeNSPrefix),N=k.tagName,W=k.rawTagName,j=k.tagExp,pe=k.attrExpPresent,Go=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&M&&S.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,S,C,!1));let Wo=S;if(Wo&&this.options.unpairedTags.indexOf(Wo.tagname)!==-1&&(S=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==R.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let de="";if(j.length>0&&j.lastIndexOf("/")===j.length-1)_=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=k.closeIndex;else{let An=this.readStopNodeData(h,W,Go+1);if(!An)throw new Error(`Unexpected end of ${W}`);_=An.i,de=An.tagContent}let Cn=new r(N);N!==j&&pe&&(Cn[":@"]=this.buildAttributesMap(j,C,N)),de&&(de=this.parseTextData(de,N,C,!0,pe,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Cn.add(this.options.textNodeName,de),this.addChild(S,Cn,C)}else{if(j.length>0&&j.lastIndexOf("/")===j.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),j=N):j=j.substr(0,j.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let de=new r(N);N!==j&&pe&&(de[":@"]=this.buildAttributesMap(j,C,N)),this.addChild(S,de,C),C=C.substr(0,C.lastIndexOf("."))}else{let de=new r(N);this.tagsNodeStack.push(S),N!==j&&pe&&(de[":@"]=this.buildAttributesMap(j,C,N)),this.addChild(S,de,C),S=de}M="",_=Go}}else M+=h[_];return R.child},"parseXml");function g(h,R,S){let M=this.options.updateTag(R.tagname,S,R[":@"]);M===!1||(typeof M=="string"&&(R.tagname=M),h.addChild(R))}i(g,"addChild"),D(g,"addChild");var I=D(function(h){if(this.options.processEntities){for(let R in this.docTypeEntities){let S=this.docTypeEntities[R];h=h.replace(S.regx,S.val)}for(let R in this.lastEntities){let S=this.lastEntities[R];h=h.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let S=this.htmlEntities[R];h=h.replace(S.regex,S.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function b(h,R,S,M){return h&&(M===void 0&&(M=Object.keys(R.child).length===0),h=this.parseTextData(h,R.tagname,S,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,M),h!==void 0&&h!==""&&R.add(this.options.textNodeName,h),h=""),h}i(b,"saveTextToParentTag"),D(b,"saveTextToParentTag");function x(h,R,S){let M="*."+S;for(let C in h){let _=h[C];if(M===_||R===_)return!0}return!1}i(x,"isItStopNode"),D(x,"isItStopNode");function L(h,R,S=">"){let M,C="";for(let _=R;_<h.length;_++){let F=h[_];if(M)F===M&&(M="");else if(F==='"'||F==="'")M=F;else if(F===S[0])if(S[1]){if(h[_+1]===S[1])return{data:C,index:_}}else return{data:C,index:_};else F===" "&&(F=" ");C+=F}}i(L,"tagExpWithClosingIndex"),D(L,"tagExpWithClosingIndex");function f(h,R,S,M){let C=h.indexOf(R,S);if(C===-1)throw new Error(M);return C+R.length-1}i(f,"findClosingIndex"),D(f,"findClosingIndex");function P(h,R,S,M=">"){let C=L(h,R+1,M);if(!C)return;let _=C.data,F=C.index,k=_.search(/\s/),N=_,W=!0;k!==-1&&(N=_.substring(0,k),_=_.substring(k+1).trimStart());let j=N;if(S){let pe=N.indexOf(":");pe!==-1&&(N=N.substr(pe+1),W=N!==C.data.substr(pe+1))}return{tagName:N,tagExp:_,closeIndex:F,attrExpPresent:W,rawTagName:j}}i(P,"readTagExp"),D(P,"readTagExp");function O(h,R,S){let M=S,C=1;for(;S<h.length;S++)if(h[S]==="<")if(h[S+1]==="/"){let _=f(h,">",S,`${R} is not closed`);if(h.substring(S+2,_).trim()===R&&(C--,C===0))return{tagContent:h.substring(M,S),i:_};S=_}else if(h[S+1]==="?")S=f(h,"?>",S+1,"StopNode is not closed.");else if(h.substr(S+1,3)==="!--")S=f(h,"-->",S+3,"StopNode is not closed.");else if(h.substr(S+1,2)==="![")S=f(h,"]]>",S,"StopNode is not closed.")-2;else{let _=P(h,S,">");_&&((_&&_.tagName)===R&&_.tagExp[_.tagExp.length-1]!=="/"&&C++,S=_.closeIndex)}}i(O,"readStopNodeData"),D(O,"readStopNodeData");function H(h,R,S){if(R&&typeof h=="string"){let M=h.trim();return M==="true"?!0:M==="false"?!1:s(h,S)}else return n.isExist(h)?h:""}i(H,"parseValue"),D(H,"parseValue"),e.exports=a}}),Wd=be({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),D(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let b=n(m[g],u,I),x=s(b,u);m[":@"]?o(b,m[":@"],I,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(b)):u.isArray(g,I,x)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),D(n,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),D(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),D(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),D(s,"isLeafTag"),t.prettify=e}}),Kd=be({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=Bd(),r=Gd(),{prettify:o}=Wd(),s=xa(),a=class{static{i(this,"XMLParser2")}static{D(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=n(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),Jd=be({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
40
- `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}i(r,"toXml"),D(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let x=l[b],L=s(x);if(L===void 0)continue;let f="";if(p.length===0?f=L:f=`${p}.${L}`,L===d.textNodeName){let R=x[L];u(f,d)||(R=d.tagValueProcessor(L,R),R=c(R,d)),I&&(g+=m),g+=R,I=!1;continue}else if(L===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${x[L][0][d.textNodeName]}]]>`,I=!1;continue}else if(L===d.commentPropName){g+=m+`<!--${x[L][0][d.textNodeName]}-->`,I=!0;continue}else if(L[0]==="?"){let R=a(x[":@"],d),S=L==="?xml"?"":m,M=x[L][0][d.textNodeName];M=M.length!==0?" "+M:"",g+=S+`<${L}${M}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let O=a(x[":@"],d),H=m+`<${L}${O}`,h=o(x[L],d,f,P);d.unpairedTags.indexOf(L)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!h||h.length===0)&&d.suppressEmptyNode?g+=H+"/>":h&&h.endsWith(">")?g+=H+`>${h}${m}</${L}>`:(g+=H+">",h&&m!==""&&(h.includes("/>")||h.includes("</"))?g+=m+d.indentBy+h+m:g+=h,g+=`</${L}>`),I=!0}return g}i(o,"arrToStr"),D(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),D(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),D(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),D(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),D(c,"replaceEntitiesValue"),e.exports=r}}),Yd=be({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=Jd(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
36
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(ku,"reduceToSingleString")});var ki=Ge(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.format=void 0;var Mu=Oi(),Du=Ni(),Hu=i((t,...e)=>(0,Mu.format)(Du.inspect,t,e),"format");Zt.format=Hu});var _e=Ge(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.debug=Ae.withoutEnv=Ae.Debugger=void 0;var Uu=vi(),Zu=ki(),qt=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Uu.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,Zu.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ae.Debugger=qt;var $t=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Mi(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Mi,"extract");var ct;function qu(t){t||(t=[]),typeof t=="string"&&(t=Mi(t)),ct=new $t(t)}i(qu,"withoutEnv");Ae.withoutEnv=qu;function $u(t){let e=globalThis.DEBUG;ct||(ct=new $t(Mi(e)));let n=new qt(ct,t);return ct.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i($u,"debug");Ae.debug=$u});var Sa=Ge((wO,Oa)=>{"use strict";var Bd=Object.defineProperty,zd=Object.getOwnPropertyNames,D=i((t,e)=>Bd(t,"name",{value:e,configurable:!0}),"__name"),we=i((t,e)=>i(function(){return e||(0,t[zd(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),$o=we({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":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=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",o=new RegExp("^"+r+"$"),s=D(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let m=d.length;for(let g=0;g<m;g++)p.push(d[g]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=D(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let m=0;m<p;m++)l==="strict"?u[d[m]]=[c[d[m]]]:u[d[m]]=c[d[m]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),va=we({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=$o(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(h,P){P=Object.assign({},n,P);let v=[],H=!1,f=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let R=0;R<h.length;R++)if(h[R]==="<"&&h[R+1]==="?"){if(R+=2,R=o(h,R),R.err)return R}else if(h[R]==="<"){let S=R;if(R++,h[R]==="!"){R=s(h,R);continue}else{let M=!1;h[R]==="/"&&(M=!0,R++);let C="";for(;R<h.length&&h[R]!==">"&&h[R]!==" "&&h[R]!==" "&&h[R]!==`
37
+ `&&h[R]!=="\r";R++)C+=h[R];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),R--),!b(C)){let k;return C.trim().length===0?k="Invalid space after '<'.":k="Tag '"+C+"' is an invalid name.",g("InvalidTag",k,T(h,R))}let L=c(h,R);if(L===!1)return g("InvalidAttr","Attributes for '"+C+"' have open quote.",T(h,R));let F=L.value;if(R=L.index,F[F.length-1]==="/"){let k=R-F.length;F=F.substring(0,F.length-1);let N=d(F,P);if(N===!0)H=!0;else return g(N.err.code,N.err.msg,T(h,k+N.err.line))}else if(M)if(L.tagClosed){if(F.trim().length>0)return g("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",T(h,S));{let k=v.pop();if(C!==k.tagName){let N=T(h,k.tagStartPos);return g("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+C+"'.",T(h,S))}v.length==0&&(f=!0)}}else return g("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",T(h,R));else{let k=d(F,P);if(k!==!0)return g(k.err.code,k.err.msg,T(h,R-F.length+k.err.line));if(f===!0)return g("InvalidXml","Multiple possible root nodes found.",T(h,R));P.unpairedTags.indexOf(C)!==-1||v.push({tagName:C,tagStartPos:S}),H=!0}for(R++;R<h.length;R++)if(h[R]==="<")if(h[R+1]==="!"){R++,R=s(h,R);continue}else if(h[R+1]==="?"){if(R=o(h,++R),R.err)return R}else break;else if(h[R]==="&"){let k=m(h,R);if(k==-1)return g("InvalidChar","char '&' is not expected.",T(h,R));R=k}else if(f===!0&&!r(h[R]))return g("InvalidXml","Extra text at the end",T(h,R));h[R]==="<"&&R--}}else{if(r(h[R]))continue;return g("InvalidChar","char '"+h[R]+"' is not expected.",T(h,R))}if(H){if(v.length==1)return g("InvalidTag","Unclosed tag '"+v[0].tagName+"'.",T(h,v[0].tagStartPos));if(v.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(v.map(R=>R.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return g("InvalidXml","Start tag expected.",1);return!0};function r(h){return h===" "||h===" "||h===`
38
+ `||h==="\r"}i(r,"isWhiteSpace"),D(r,"isWhiteSpace");function o(h,P){let v=P;for(;P<h.length;P++)if(h[P]=="?"||h[P]==" "){let H=h.substr(v,P-v);if(P>5&&H==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",T(h,P));if(h[P]=="?"&&h[P+1]==">"){P++;break}else continue}return P}i(o,"readPI"),D(o,"readPI");function s(h,P){if(h.length>P+5&&h[P+1]==="-"&&h[P+2]==="-"){for(P+=3;P<h.length;P++)if(h[P]==="-"&&h[P+1]==="-"&&h[P+2]===">"){P+=2;break}}else if(h.length>P+8&&h[P+1]==="D"&&h[P+2]==="O"&&h[P+3]==="C"&&h[P+4]==="T"&&h[P+5]==="Y"&&h[P+6]==="P"&&h[P+7]==="E"){let v=1;for(P+=8;P<h.length;P++)if(h[P]==="<")v++;else if(h[P]===">"&&(v--,v===0))break}else if(h.length>P+9&&h[P+1]==="["&&h[P+2]==="C"&&h[P+3]==="D"&&h[P+4]==="A"&&h[P+5]==="T"&&h[P+6]==="A"&&h[P+7]==="["){for(P+=8;P<h.length;P++)if(h[P]==="]"&&h[P+1]==="]"&&h[P+2]===">"){P+=2;break}}return P}i(s,"readCommentAndCDATA"),D(s,"readCommentAndCDATA");var a='"',u="'";function c(h,P){let v="",H="",f=!1;for(;P<h.length;P++){if(h[P]===a||h[P]===u)H===""?H=h[P]:H!==h[P]||(H="");else if(h[P]===">"&&H===""){f=!0;break}v+=h[P]}return H!==""?!1:{value:v,index:P,tagClosed:f}}i(c,"readAttributeStr"),D(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(h,P){let v=e.getAllMatches(h,l),H={};for(let f=0;f<v.length;f++){if(v[f][1].length===0)return g("InvalidAttr","Attribute '"+v[f][2]+"' has no space in starting.",_(v[f]));if(v[f][3]!==void 0&&v[f][4]===void 0)return g("InvalidAttr","Attribute '"+v[f][2]+"' is without value.",_(v[f]));if(v[f][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+v[f][2]+"' is not allowed.",_(v[f]));let R=v[f][2];if(!I(R))return g("InvalidAttr","Attribute '"+R+"' is an invalid name.",_(v[f]));if(!H.hasOwnProperty(R))H[R]=1;else return g("InvalidAttr","Attribute '"+R+"' is repeated.",_(v[f]))}return!0}i(d,"validateAttributeString"),D(d,"validateAttributeString");function p(h,P){let v=/\d/;for(h[P]==="x"&&(P++,v=/[\da-fA-F]/);P<h.length;P++){if(h[P]===";")return P;if(!h[P].match(v))break}return-1}i(p,"validateNumberAmpersand"),D(p,"validateNumberAmpersand");function m(h,P){if(P++,h[P]===";")return-1;if(h[P]==="#")return P++,p(h,P);let v=0;for(;P<h.length;P++,v++)if(!(h[P].match(/\w/)&&v<20)){if(h[P]===";")break;return-1}return P}i(m,"validateAmpersand"),D(m,"validateAmpersand");function g(h,P,v){return{err:{code:h,msg:P,line:v.line||v,col:v.col}}}i(g,"getErrorObject"),D(g,"getErrorObject");function I(h){return e.isName(h)}i(I,"validateAttrName"),D(I,"validateAttrName");function b(h){return e.isName(h)}i(b,"validateTagName"),D(b,"validateTagName");function T(h,P){let v=h.substring(0,P).split(/\r?\n/);return{line:v.length,col:v[v.length-1].length+1}}i(T,"getLineNumberForPosition"),D(T,"getLineNumberForPosition");function _(h){return h.startIndex+h[1].length}i(_,"getPositionFromMatch"),D(_,"getPositionFromMatch")}}),jd=we({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,s){return r}},n=D(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),Vd=we({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=class{static{i(this,"XmlNode")}static{D(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=n}}),Gd=we({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=$o();function r(p,m){let g={};if(p[m+3]==="O"&&p[m+4]==="C"&&p[m+5]==="T"&&p[m+6]==="Y"&&p[m+7]==="P"&&p[m+8]==="E"){m=m+9;let I=1,b=!1,T=!1,_="";for(;m<p.length;m++)if(p[m]==="<"&&!T){if(b&&a(p,m))m+=7,[entityName,val,m]=o(p,m+1),val.indexOf("&")===-1&&(g[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&u(p,m))m+=8;else if(b&&c(p,m))m+=8;else if(b&&l(p,m))m+=9;else if(s)T=!0;else throw new Error("Invalid DOCTYPE");I++,_=""}else if(p[m]===">"){if(T?p[m-1]==="-"&&p[m-2]==="-"&&(T=!1,I--):I--,I===0)break}else p[m]==="["?b=!0:_+=p[m];if(I!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}i(r,"readDocType"),D(r,"readDocType");function o(p,m){let g="";for(;m<p.length&&p[m]!=="'"&&p[m]!=='"';m++)g+=p[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let I=p[m++],b="";for(;m<p.length&&p[m]!==I;m++)b+=p[m];return[g,b,m]}i(o,"readEntityExp"),D(o,"readEntityExp");function s(p,m){return p[m+1]==="!"&&p[m+2]==="-"&&p[m+3]==="-"}i(s,"isComment"),D(s,"isComment");function a(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="N"&&p[m+4]==="T"&&p[m+5]==="I"&&p[m+6]==="T"&&p[m+7]==="Y"}i(a,"isEntity"),D(a,"isEntity");function u(p,m){return p[m+1]==="!"&&p[m+2]==="E"&&p[m+3]==="L"&&p[m+4]==="E"&&p[m+5]==="M"&&p[m+6]==="E"&&p[m+7]==="N"&&p[m+8]==="T"}i(u,"isElement"),D(u,"isElement");function c(p,m){return p[m+1]==="!"&&p[m+2]==="A"&&p[m+3]==="T"&&p[m+4]==="T"&&p[m+5]==="L"&&p[m+6]==="I"&&p[m+7]==="S"&&p[m+8]==="T"}i(c,"isAttlist"),D(c,"isAttlist");function l(p,m){return p[m+1]==="!"&&p[m+2]==="N"&&p[m+3]==="O"&&p[m+4]==="T"&&p[m+5]==="A"&&p[m+6]==="T"&&p[m+7]==="I"&&p[m+8]==="O"&&p[m+9]==="N"}i(l,"isNotation"),D(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),D(d,"validateEntityName"),e.exports=r}}),Wd=we({"../../node_modules/strnum/strnum.js"(t,e){var n=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(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 o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&n.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],m=d[2],g=a(d[3]),I=d[4]||d[6];if(!c.leadingZeros&&m.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&m.length>0&&!p&&l[1]!==".")return u;{let b=Number(l),T=""+b;return T.search(/[eE]/)!==-1||I?c.eNotation?b:u:l.indexOf(".")!==-1?T==="0"&&g===""||T===g||p&&T==="-"+g?b:u:m?g===T||p+g===T?b:u:l===T||l===p+T?b:u}}else return u}}i(s,"toNumber"),D(s,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}i(a,"trimZeros"),D(a,"trimZeros"),e.exports=s}}),Jd=we({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=$o(),r=Vd(),o=Gd(),s=Wd(),a=class{static{i(this,"OrderedObjParser")}static{D(this,"OrderedObjParser")}constructor(f){this.options=f,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"}},this.addExternalEntities=u,this.parseXml=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=T,this.replaceEntitiesValue=I,this.readStopNodeData=v,this.saveTextToParentTag=b,this.addChild=g}};function u(f){let R=Object.keys(f);for(let S=0;S<R.length;S++){let M=R[S];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:f[M]}}}i(u,"addExternalEntities"),D(u,"addExternalEntities");function c(f,R,S,M,C,L,F){if(f!==void 0&&(this.options.trimValues&&!M&&(f=f.trim()),f.length>0)){F||(f=this.replaceEntitiesValue(f));let k=this.options.tagValueProcessor(R,f,S,C,L);return k==null?f:typeof k!=typeof f||k!==f?k:this.options.trimValues?H(f,this.options.parseTagValue,this.options.numberParseOptions):f.trim()===f?H(f,this.options.parseTagValue,this.options.numberParseOptions):f}}i(c,"parseTextData"),D(c,"parseTextData");function l(f){if(this.options.removeNSPrefix){let R=f.split(":"),S=f.charAt(0)==="/"?"/":"";if(R[0]==="xmlns")return"";R.length===2&&(f=S+R[1])}return f}i(l,"resolveNameSpace"),D(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(f,R,S){if(!this.options.ignoreAttributes&&typeof f=="string"){let M=n.getAllMatches(f,d),C=M.length,L={};for(let F=0;F<C;F++){let k=this.resolveNameSpace(M[F][1]),N=M[F][4],W=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(W=this.options.transformAttributeName(W)),W==="__proto__"&&(W="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let j=this.options.attributeValueProcessor(k,N,R);j==null?L[W]=N:typeof j!=typeof N||j!==N?L[W]=j:L[W]=H(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[W]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let F={};return F[this.options.attributesGroupName]=L,F}return L}}i(p,"buildAttributesMap"),D(p,"buildAttributesMap");var m=D(function(f){f=f.replace(/\r\n?/g,`
39
+ `);let R=new r("!xml"),S=R,M="",C="";for(let L=0;L<f.length;L++)if(f[L]==="<")if(f[L+1]==="/"){let k=h(f,">",L,"Closing Tag is not closed."),N=f.substring(L+2,k).trim();if(this.options.removeNSPrefix){let pe=N.indexOf(":");pe!==-1&&(N=N.substr(pe+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(M=this.saveTextToParentTag(M,S,C));let W=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let j=0;W&&this.options.unpairedTags.indexOf(W)!==-1?(j=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):j=C.lastIndexOf("."),C=C.substring(0,j),S=this.tagsNodeStack.pop(),M="",L=k}else if(f[L+1]==="?"){let k=P(f,L,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,S,C),!(this.options.ignoreDeclaration&&k.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(k.tagName);N.add(this.options.textNodeName,""),k.tagName!==k.tagExp&&k.attrExpPresent&&(N[":@"]=this.buildAttributesMap(k.tagExp,C,k.tagName)),this.addChild(S,N,C)}L=k.closeIndex+1}else if(f.substr(L+1,3)==="!--"){let k=h(f,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let N=f.substring(L+4,k-2);M=this.saveTextToParentTag(M,S,C),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}L=k}else if(f.substr(L+1,2)==="!D"){let k=o(f,L);this.docTypeEntities=k.entities,L=k.i}else if(f.substr(L+1,2)==="!["){let k=h(f,"]]>",L,"CDATA is not closed.")-2,N=f.substring(L+9,k);M=this.saveTextToParentTag(M,S,C);let W=this.parseTextData(N,S.tagname,C,!0,!1,!0,!0);W==null&&(W=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,W),L=k+2}else{let k=P(f,L,this.options.removeNSPrefix),N=k.tagName,W=k.rawTagName,j=k.tagExp,pe=k.attrExpPresent,Jo=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&M&&S.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,S,C,!1));let Ko=S;if(Ko&&this.options.unpairedTags.indexOf(Ko.tagname)!==-1&&(S=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==R.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let de="";if(j.length>0&&j.lastIndexOf("/")===j.length-1)L=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)L=k.closeIndex;else{let _n=this.readStopNodeData(f,W,Jo+1);if(!_n)throw new Error(`Unexpected end of ${W}`);L=_n.i,de=_n.tagContent}let An=new r(N);N!==j&&pe&&(An[":@"]=this.buildAttributesMap(j,C,N)),de&&(de=this.parseTextData(de,N,C,!0,pe,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),An.add(this.options.textNodeName,de),this.addChild(S,An,C)}else{if(j.length>0&&j.lastIndexOf("/")===j.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),j=N):j=j.substr(0,j.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let de=new r(N);N!==j&&pe&&(de[":@"]=this.buildAttributesMap(j,C,N)),this.addChild(S,de,C),C=C.substr(0,C.lastIndexOf("."))}else{let de=new r(N);this.tagsNodeStack.push(S),N!==j&&pe&&(de[":@"]=this.buildAttributesMap(j,C,N)),this.addChild(S,de,C),S=de}M="",L=Jo}}else M+=f[L];return R.child},"parseXml");function g(f,R,S){let M=this.options.updateTag(R.tagname,S,R[":@"]);M===!1||(typeof M=="string"&&(R.tagname=M),f.addChild(R))}i(g,"addChild"),D(g,"addChild");var I=D(function(f){if(this.options.processEntities){for(let R in this.docTypeEntities){let S=this.docTypeEntities[R];f=f.replace(S.regx,S.val)}for(let R in this.lastEntities){let S=this.lastEntities[R];f=f.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let R in this.htmlEntities){let S=this.htmlEntities[R];f=f.replace(S.regex,S.val)}f=f.replace(this.ampEntity.regex,this.ampEntity.val)}return f},"replaceEntitiesValue");function b(f,R,S,M){return f&&(M===void 0&&(M=Object.keys(R.child).length===0),f=this.parseTextData(f,R.tagname,S,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,M),f!==void 0&&f!==""&&R.add(this.options.textNodeName,f),f=""),f}i(b,"saveTextToParentTag"),D(b,"saveTextToParentTag");function T(f,R,S){let M="*."+S;for(let C in f){let L=f[C];if(M===L||R===L)return!0}return!1}i(T,"isItStopNode"),D(T,"isItStopNode");function _(f,R,S=">"){let M,C="";for(let L=R;L<f.length;L++){let F=f[L];if(M)F===M&&(M="");else if(F==='"'||F==="'")M=F;else if(F===S[0])if(S[1]){if(f[L+1]===S[1])return{data:C,index:L}}else return{data:C,index:L};else F===" "&&(F=" ");C+=F}}i(_,"tagExpWithClosingIndex"),D(_,"tagExpWithClosingIndex");function h(f,R,S,M){let C=f.indexOf(R,S);if(C===-1)throw new Error(M);return C+R.length-1}i(h,"findClosingIndex"),D(h,"findClosingIndex");function P(f,R,S,M=">"){let C=_(f,R+1,M);if(!C)return;let L=C.data,F=C.index,k=L.search(/\s/),N=L,W=!0;k!==-1&&(N=L.substring(0,k),L=L.substring(k+1).trimStart());let j=N;if(S){let pe=N.indexOf(":");pe!==-1&&(N=N.substr(pe+1),W=N!==C.data.substr(pe+1))}return{tagName:N,tagExp:L,closeIndex:F,attrExpPresent:W,rawTagName:j}}i(P,"readTagExp"),D(P,"readTagExp");function v(f,R,S){let M=S,C=1;for(;S<f.length;S++)if(f[S]==="<")if(f[S+1]==="/"){let L=h(f,">",S,`${R} is not closed`);if(f.substring(S+2,L).trim()===R&&(C--,C===0))return{tagContent:f.substring(M,S),i:L};S=L}else if(f[S+1]==="?")S=h(f,"?>",S+1,"StopNode is not closed.");else if(f.substr(S+1,3)==="!--")S=h(f,"-->",S+3,"StopNode is not closed.");else if(f.substr(S+1,2)==="![")S=h(f,"]]>",S,"StopNode is not closed.")-2;else{let L=P(f,S,">");L&&((L&&L.tagName)===R&&L.tagExp[L.tagExp.length-1]!=="/"&&C++,S=L.closeIndex)}}i(v,"readStopNodeData"),D(v,"readStopNodeData");function H(f,R,S){if(R&&typeof f=="string"){let M=f.trim();return M==="true"?!0:M==="false"?!1:s(f,S)}else return n.isExist(f)?f:""}i(H,"parseValue"),D(H,"parseValue"),e.exports=a}}),Kd=we({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),D(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let m=a[p],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let b=n(m[g],u,I),T=s(b,u);m[":@"]?o(b,m[":@"],I,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[g]!==void 0&&d.hasOwnProperty(g)?(Array.isArray(d[g])||(d[g]=[d[g]]),d[g].push(b)):u.isArray(g,I,T)?d[g]=[b]:d[g]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),D(n,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),D(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let m=0;m<p;m++){let g=d[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}i(o,"assignAttributes"),D(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),D(s,"isLeafTag"),t.prettify=e}}),Yd=we({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=jd(),r=Jd(),{prettify:o}=Kd(),s=va(),a=class{static{i(this,"XMLParser2")}static{D(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=n(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),Qd=we({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
40
+ `;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}i(r,"toXml"),D(r,"toXml");function o(l,d,p,m){let g="",I=!1;for(let b=0;b<l.length;b++){let T=l[b],_=s(T);if(_===void 0)continue;let h="";if(p.length===0?h=_:h=`${p}.${_}`,_===d.textNodeName){let R=T[_];u(h,d)||(R=d.tagValueProcessor(_,R),R=c(R,d)),I&&(g+=m),g+=R,I=!1;continue}else if(_===d.cdataPropName){I&&(g+=m),g+=`<![CDATA[${T[_][0][d.textNodeName]}]]>`,I=!1;continue}else if(_===d.commentPropName){g+=m+`<!--${T[_][0][d.textNodeName]}-->`,I=!0;continue}else if(_[0]==="?"){let R=a(T[":@"],d),S=_==="?xml"?"":m,M=T[_][0][d.textNodeName];M=M.length!==0?" "+M:"",g+=S+`<${_}${M}${R}?>`,I=!0;continue}let P=m;P!==""&&(P+=d.indentBy);let v=a(T[":@"],d),H=m+`<${_}${v}`,f=o(T[_],d,h,P);d.unpairedTags.indexOf(_)!==-1?d.suppressUnpairedNode?g+=H+">":g+=H+"/>":(!f||f.length===0)&&d.suppressEmptyNode?g+=H+"/>":f&&f.endsWith(">")?g+=H+`>${f}${m}</${_}>`:(g+=H+">",f&&m!==""&&(f.includes("/>")||f.includes("</"))?g+=m+d.indentBy+f+m:g+=f,g+=`</${_}>`),I=!0}return g}i(o,"arrToStr"),D(o,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let m=d[p];if(l.hasOwnProperty(m)&&m!==":@")return m}}i(s,"propName"),D(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let m in l){if(!l.hasOwnProperty(m))continue;let g=d.attributeValueProcessor(m,l[m]);g=c(g,d),g===!0&&d.suppressBooleanAttributes?p+=` ${m.substr(d.attributeNamePrefix.length)}`:p+=` ${m.substr(d.attributeNamePrefix.length)}="${g}"`}return p}i(a,"attr_to_str"),D(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let m in d.stopNodes)if(d.stopNodes[m]===l||d.stopNodes[m]==="*."+p)return!0;return!1}i(u,"isStopNode"),D(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let m=d.entities[p];l=l.replace(m.regex,m.val)}return l}i(c,"replaceEntitiesValue"),D(c,"replaceEntitiesValue"),e.exports=r}}),Xd=we({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=Qd(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
41
41
  `,this.newLine=`
42
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),D(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?n(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let x=c[m][b];typeof x>"u"||(x===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof x=="object"?this.options.oneListGroup?I+=this.j2x(x,l+1).val:I+=this.processTextOrObjNode(x,m,l):I+=this.buildTextValNode(x,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),D(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),D(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),D(u,"isAttribute"),e.exports=o}}),Qd=xa(),Xd=Kd(),ep=Yd();va.exports={XMLParser:Xd,XMLValidator:Qd,XMLBuilder:ep};});var q=class extends Error{static{i(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},A=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{i(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},_t=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var w=class t{static{i(this,"Environment")}config;static#e;static initialize(e){this.#e||(this.#e=new t(e))}static get instance(){if(!this.#e)throw new q("Environment has not been initialized");return this.#e}constructor({build:e,runtime:n}){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};Function.prototype.toString=function(){return"[native code]"};var Nt=globalThis,Ko=Nt.caches;if(Ko){let t=Ko.open;Nt.caches.open=function(e){let n=w.instance.deploymentName??w.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Nt.caches.default,Object.freeze(Nt.caches)}var Jo=new Map,_n=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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:n};this.#r.push(e),this.#n.set(e,s)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Ge=class{static{i(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Jo.get(e);r||(r=new _n(n),Jo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Nn="__zuplo-expiry-header",it=class{static{i(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let s=o.headers.get(Nn);if(!s){try{await n.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 n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Nn,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await s.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(Nn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:n});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 Q=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ge(r),this.#n=new it(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,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 Yo="zuplo-request-id",De="zp-rid",kn="zp-body-removed",He="cf-ray",Qo="x-real-ip",Mn="cf-ipcity",Dn="cf-ipcontinent",Hn="cf-ipcountry",Un="cf-iplongitude",Zn="cf-iplatitude",Xo="cf-region",ei="cf-region-code",ti="cf-metro-code",ni="cf-postal-code",ri="cf-timezone",oi="zp-ipcity",ii="zp-ipcontinent",si="zp-ipcountry",ai="zp-iplongitude",ui="zp-iplatitude",ci="true-client-ip",qn="zp-asn",$n="zp-asorg",Fn="zp-colo",Bn="zp-postalcode",zn="zp-metrocode",jn="zp-region",Vn="zp-regioncode",Gn="zp-timezone",li=[Mn,Dn,Hn,Un,Zn,qn,$n,Fn,Bn,zn,jn,Vn,Gn],di=["zp-","cf-"],pi=[De,He,kn],mi=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],st="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",kt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var fs=Se(Ae());import{trace as gs}from"@opentelemetry/api";import{SpanStatusCode as qu,trace as $u}from"@opentelemetry/api";import{SpanStatusCode as ir,trace as sr}from"@opentelemetry/api";var _i=i(t=>(e,n)=>t(e,n),"globalRequestHandlerProxy");function Ni(t){_i=t}i(Ni,"setTelemetryInitFunction");var ki=i(t=>_i(t),"proxyHandler");var Le=class{static{i(this,"RuntimePlugin")}},Ie=class extends Le{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},$t=class extends Ie{static{i(this,"MeteringPlugin")}},ut=class extends Le{static{i(this,"TelemetryPlugin")}};var ct=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ze=class{static{i(this,"ProblemResponseFormatter")}static async format(e,n,r){return await ct.problemResponseFormat(e,n,r)}};function Ft(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ft(n)}return Object.freeze(t)}i(Ft,"deepFreeze");var z=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Ft(this.#e)}get params(){return Ft(this.#t)}user};var lt={},xe=[],nr=[],rr=[],or=[];var Bt={addPlugin(t){xe.push(t)},addRequestHook(t){nr.push(t)},addResponseSendingHook(t){rr.push(t)},addResponseSendingFinalHook(t){or.push(t)}},Di=i(async(t,e)=>{if(nr.length===0)return t;let n=sr.getTracer("extension");return n.startActiveSpan("onRequest",async r=>{try{let o=t;for(let s of nr){let a=await n.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:ir.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Hi=i(async(t,e,n)=>{if(rr.length===0)return t;let r=sr.getTracer("extension");return r.startActiveSpan("onResponseSending",async o=>{try{let s=t;for(let a of rr)await r.startActiveSpan(a.name,async u=>{let c=await a(t,e,n);if(c instanceof Response)s=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:ir.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ui=i(async(t,e,n)=>{if(or.length===0)return;let r=sr.getTracer("extension");return r.startActiveSpan("onResponseSendingFinal",async o=>{try{for(let s of or)await r.startActiveSpan(s.name,async a=>{try{await s(t,e,n)}catch(u){throw a.recordException(u),a.setStatus({code:ir.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Mi=!1;async function Zi(t=()=>Promise.resolve()){if(!Mi){await t(Bt),lt.value=Bt;for(let e of xe)if(e instanceof ut){let{requestHandlerProxy:n}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});Ni(n)}for(let e of xe)e instanceof Ie&&await e.initialize(Bt);ct.setProblemResponseFormat(Bt.problemResponseFormat),Mi=!0}}i(Zi,"initializeRuntime");var ar={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ur(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ar.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ar.Json)||!e?JSON.stringify(t):t}i(ur,"serialize");function dt(t){return X.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(X.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var J=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>$u.getTracer("pipeline").startActiveSpan("handler",async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=n.errorHandler(r,o,u);return a.setStatus({code:qu.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:n,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let x=a.pop();return x?x(o,s,n,u):await this.#e(async P=>{let O=await r(P,s);return Fu(O)},n)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(dt(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new pt(o,l);s.dispatchEvent(p);let m=te.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return s.log.error(b),n.errorHandler(o,s,b)}try{I=await m.onResponseSending(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}try{I=await Hi(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}s.dispatchEvent(new mt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Ui(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function Fu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(ur(t),{headers:{"content-type":"application/json"}})}i(Fu,"resultToResponse");var _e=class extends Le{static{i(this,"MetricsPlugin")}};var B=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new q(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var $=class{static{i(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{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(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var zt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,B.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:s}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!u.ok){let c=await u.text();B.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var K=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=s,this.version=gt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},gt={name:"__system-no-version",pathPrefix:""};var ne=i(async(t,e,n,r)=>{let o=new Date,s=Date.now(),a=await r(t),u=t.headers.get(He)??void 0,c=t.headers.get(ci)??void 0,l=e.incomingRequestProperties,d;e.route instanceof K&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.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:t.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:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new zt(e)),xe.forEach(I=>{if(I instanceof _e){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var cr=i((t,e)=>{let n=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&B.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new K({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var lr=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(lr||{}),qi={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 Bu={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"},dr=Bu;function zu(t){return`${new URL(t.url).pathname}`}i(zu,"instance");function ju(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=t.headers.get(He);return r&&(n.rayId=r),n}i(ju,"trace");var Vu=i((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:zu(e),trace:ju(e,n),...r},additionalHeaders:o,statusText:dr[t.status]}),"merge"),pr=class{static{i(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?Ze.format(e,n,r):Ze.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:qi[e],...n}}},T=class extends pr{static{i(this,"HttpProblems")}static#e(e,n,r,o,s){let a=Vu(this.getProblemFromStatus(e),n,r,o,s);return Ze.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Gu}=Object.prototype,{propertyIsEnumerable:Wu}=Object.prototype;function mr(t){return Gu.call(t)}i(mr,"toString");function ae(t){return typeof t=="string"}i(ae,"isString");function We(t){return ae(t)&&t!==""}i(We,"isNonEmptyString");function $i(t){return mr(t)==="[object RegExp]"}i($i,"isRegexp");function Fi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Wu.call(t,e))]}i(Fi,"getOwnEnumerableKeys");function qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(qe,"isObject");function gr(t){return typeof t=="number"&&!isNaN(t)}i(gr,"isNumber");function fr(t){return t===!0||t===!1}i(fr,"isBoolean");function Bi(t){return typeof t>"u"}i(Bi,"isUndefined");function zi(t){return Bi(t)||t===null}i(zi,"isUndefinedOrNull");function ft(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(ft,"isErrorLike");var ji=new Map;function Ke(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=ji.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){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 ji.set(t,r),r}i(Ke,"statusCodesStringToNumberArray");function $e(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(s=>{if(o===void 0)throw new A(`Error applying ${n} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i($e,"getValueFromRequestUser");function Fe(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(ae(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(Fe,"parseValueToStringArray");function Vi(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!qe(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!We(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!gr(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!fr(n.allowCredentials))throw new y("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(n,"allowedHeaders"),o=hr(n,"allowedMethods"),s=hr(n,"exposeHeaders"),a;try{a=Fe(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.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 n.maxAge=="number"?n.maxAge.toString():void 0}})}i(Vi,"parseCorsPolicies");function hr(t,e){let n;if(t[e]!==void 0)try{n=Fe(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}i(hr,"parseOptionalProperty");var jt=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Vt=i((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var yr=i((t,e)=>{let n=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 T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=Ku(l,d,p,g,n);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),s=new K({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),Ku=i((t,e,n,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"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 y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=jt(a.allowedOrigins,n);return u?{isValid:!0,headers:Vt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Gi=i((t,e)=>{let n=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new K({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var br=new K({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Wi=i((t,e)=>{let n=i(async(o,s)=>{let a=lt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new J({processors:[ne],handler:n,gateway:e});t.addRoute(br,r.execute)},"registerNotMatchedHandler");var Ju=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ki=i(t=>{Ju.forEach(e=>t.delete(e))},"stripCorsHeaders"),Gt=i(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Ki(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(t);if(!(s instanceof Response))throw new q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Yu(o,n.routeData.corsPolicies),u=Qu(t,a),c=new Headers(s.headers);return Ki(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"),Yu=i((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Qu=i((t,e)=>{let n=jt(e.allowedOrigins,t.headers.get("origin"));return n?Vt(e,n):{}},"getCorsHeaders");var wr=i((t,e)=>{let n=i(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Gt],handler:n,gateway:e}),o=new K({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Ji,trace as Yi}from"@opentelemetry/api";var Wt=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,n){if(!ae(n))throw new A(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n,this.policyType=Object.getPrototypeOf(this).constructor.name}},we=class extends Wt{static{i(this,"InboundPolicy")}},Ne=class extends Wt{static{i(this,"OutboundPolicy")}};var Er=class extends we{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.policyType=e.name,this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Ir=class extends Ne{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.policyType=e.name,this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},Rr=new Map;function ht(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(s=>!Rr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`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 y(`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 y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof we)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Er(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Rr.set(a.name,c)}),n.map(s=>{let a=Rr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(ht,"getInboundPolicyInstances");var Pr=new Map;function Xu(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Pr.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ne)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ir(a,s.handler.options??{},s.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Pr.set(s.name,u)}),n.map(o=>{let s=Pr.get(o);if(s===void 0)throw new A("Internal error. Policy not found in cache.");return s})}i(Xu,"getOutboundPolicyInstances");var xr=i(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=Yi.getTracer("pipeline");return await o.startActiveSpan("inbound-policies",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(c.policyName,async d=>{let p=await c.handler(u,n);if(p instanceof Request||p instanceof z||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Ji.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ec=i(t=>async(e,n,r)=>{let o=Yi.getTracer("pipeline");return await o.startActiveSpan("outbound-policies",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(c.policyName,async d=>{try{d.setAttribute("zuplo.policy.name",c.policyName),d.setAttribute("zuplo.policy.type",c.policyType);let p=await c.handler(u,n,r);if(p instanceof Response)return p;{let m=new y(`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:Ji.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Kt=i(async(t,e,n,r)=>{let o=ht(e.route,n.routeData.policies),s=Xu(e.route,n.routeData.policies);return Xi({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:n,next:r})},"policyProcessor");function Qi({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Xi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Qi,"createInternalPolicyProcessor");async function Xi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:s}){let a=xr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=ec(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}i(Xi,"executePolicyProcessor");function es(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||tc,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s);if(u===-1)u=t.length;else if(u<a){s=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(s,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=nc(l,o)}s=u+1}return n}i(es,"parse");function tc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}i(tc,"decode");function nc(t,e){try{return e(t)}catch{return t}}i(nc,"tryDecode");function ts(t,e){try{let n=/v\d+(-\d+)?/g,o=es(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(ts,"devPortalBaseURL");var ns="/__zuplo/dev-portal",rc="dev-portal-id",oc="dev-portal-host",ic="zp-account",sc="zp-project",ac="dev-portal-build",uc=`
42
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}i(o,"Builder"),D(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?n(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let m in c)if(Object.prototype.hasOwnProperty.call(c,m))if(typeof c[m]>"u")this.isAttribute(m)&&(p+="");else if(c[m]===null)this.isAttribute(m)?p+="":m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar;else if(c[m]instanceof Date)p+=this.buildTextValNode(c[m],m,"",l);else if(typeof c[m]!="object"){let g=this.isAttribute(m);if(g)d+=this.buildAttrPairStr(g,""+c[m]);else if(m===this.options.textNodeName){let I=this.options.tagValueProcessor(m,""+c[m]);p+=this.replaceEntitiesValue(I)}else p+=this.buildTextValNode(c[m],m,"",l)}else if(Array.isArray(c[m])){let g=c[m].length,I="";for(let b=0;b<g;b++){let T=c[m][b];typeof T>"u"||(T===null?m[0]==="?"?p+=this.indentate(l)+"<"+m+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+m+"/"+this.tagEndChar:typeof T=="object"?this.options.oneListGroup?I+=this.j2x(T,l+1).val:I+=this.processTextOrObjNode(T,m,l):I+=this.buildTextValNode(T,m,"",l))}this.options.oneListGroup&&(I=this.buildObjectNode(I,m,"",l)),p+=I}else if(this.options.attributesGroupName&&m===this.options.attributesGroupName){let g=Object.keys(c[m]),I=g.length;for(let b=0;b<I;b++)d+=this.buildAttrPairStr(g[b],""+c[m][g[b]])}else p+=this.processTextOrObjNode(c[m],m,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function s(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}i(s,"processTextOrObjNode"),D(s,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let m="</"+l+this.tagEndChar,g="";return l[0]==="?"&&(g="?",m=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+g+">"+c+m:this.options.commentPropName!==!1&&l===this.options.commentPropName&&g.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+g+this.tagEndChar+c+this.indentate(p)+m}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let m=this.options.tagValueProcessor(l,c);return m=this.replaceEntitiesValue(m),m===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+m+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}i(a,"indentate"),D(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}i(u,"isAttribute"),D(u,"isAttribute"),e.exports=o}}),ep=va(),tp=Yd(),np=Xd();Oa.exports={XMLParser:tp,XMLValidator:ep,XMLBuilder:np};});var Nn="2024-01-15",Yo=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Qo(){return new w({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Nn,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Yo[Nn]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"deno",__ZUPLO_AUTH_API_JWT:""}})}i(Qo,"getMockEnvironment");var w=class t{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new t(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Qo()),this.#e}constructor({build:e,runtime:n}){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};Function.prototype.toString=function(){return"[native code]"};var Lt=globalThis,Xo=Lt.caches;if(Xo){let t=Xo.open;Lt.caches.open=function(e){let n=w.instance.deploymentName??w.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Lt.caches.default,Object.freeze(Lt.caches)}var ei=new Map,kn=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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:n};this.#r.push(e),this.#n.set(e,s)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},We=class{static{i(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=ei.get(e);r||(r=new kn(n),ei.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Mn="__zuplo-expiry-header",at=class{static{i(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let s=o.headers.get(Mn);if(!s){try{await n.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 n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Mn,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await s.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(Mn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:n});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 Q=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new at(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,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 ti="zuplo-request-id",He="zp-rid",Dn="zp-body-removed",Ue="cf-ray",ni="x-real-ip",Hn="cf-ipcity",Un="cf-ipcontinent",Zn="cf-ipcountry",qn="cf-iplongitude",$n="cf-iplatitude",ri="cf-region",oi="cf-region-code",ii="cf-metro-code",si="cf-postal-code",ai="cf-timezone",ui="zp-ipcity",ci="zp-ipcontinent",li="zp-ipcountry",di="zp-iplongitude",pi="zp-iplatitude",mi="true-client-ip",Fn="zp-asn",Bn="zp-asorg",zn="zp-colo",jn="zp-postalcode",Vn="zp-metrocode",Gn="zp-region",Wn="zp-regioncode",Jn="zp-timezone",gi=[Hn,Un,Zn,qn,$n,Fn,Bn,zn,jn,Vn,Gn,Wn,Jn],fi=["zp-","cf-"],hi=[He,Ue,Dn],yi=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],ut="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Nt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",kt="system-logger";var q=class extends Error{static{i(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},A=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends A{static{i(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},Mt=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var ws=Se(_e());import{trace as bs}from"@opentelemetry/api";import{SpanStatusCode as Fu,trace as Bu}from"@opentelemetry/api";import{SpanStatusCode as ar,trace as ur}from"@opentelemetry/api";var Di=i(t=>(e,n)=>t(e,n),"globalRequestHandlerProxy");function Hi(t){Di=t}i(Hi,"setTelemetryInitFunction");var Ui=i(t=>Di(t),"proxyHandler");var Le=class{static{i(this,"RuntimePlugin")}},Te=class extends Le{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ft=class extends Te{static{i(this,"MeteringPlugin")}},lt=class extends Le{static{i(this,"TelemetryPlugin")}};var dt=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},qe=class{static{i(this,"ProblemResponseFormatter")}static async format(e,n,r){return await dt.problemResponseFormat(e,n,r)}};function Bt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Bt(n)}return Object.freeze(t)}i(Bt,"deepFreeze");var z=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Bt(this.#e)}get params(){return Bt(this.#t)}user};var pt={},xe=[],or=[],ir=[],sr=[];var zt={addPlugin(t){xe.push(t)},addRequestHook(t){or.push(t)},addResponseSendingHook(t){ir.push(t)},addResponseSendingFinalHook(t){sr.push(t)}},qi=i(async(t,e)=>{if(or.length===0)return t;let n=ur.getTracer("extension");return n.startActiveSpan("hook:onRequest",async r=>{try{let o=t;for(let s of or){let a=await n.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof z||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:ar.ERROR}),l}});if(a instanceof z)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),$i=i(async(t,e,n)=>{if(ir.length===0)return t;let r=ur.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=t;for(let a of ir)await r.startActiveSpan(a.name,async u=>{let c=await a(t,e,n);if(c instanceof Response)s=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:ar.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Fi=i(async(t,e,n)=>{if(sr.length===0)return;let r=ur.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of sr)await r.startActiveSpan(s.name,async a=>{try{await s(t,e,n)}catch(u){throw a.recordException(u),a.setStatus({code:ar.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Zi=!1;async function Bi(t=()=>Promise.resolve()){if(!Zi){await t(zt),pt.value=zt;for(let e of xe)if(e instanceof lt){let{requestHandlerProxy:n}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});Hi(n)}for(let e of xe)e instanceof Te&&await e.initialize(zt);dt.setProblemResponseFormat(zt.problemResponseFormat),Zi=!0}}i(Bi,"initializeRuntime");var cr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function lr(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(cr.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(cr.Json)||!e?JSON.stringify(t):t}i(lr,"serialize");function Je(t){return ee.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(ee.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(Je,"isSystemRoute");var K=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>Bu.getTracer("pipeline").startActiveSpan("handler",async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=n.errorHandler(r,o,u);return a.setStatus({code:Fu.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:n,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let T=a.pop();return T?T(o,s,n,u):await this.#e(async P=>{let v=await r(P,s);return zu(v)},n)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Je(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new mt(o,l);s.dispatchEvent(p);let m=te.getContextExtensions(s),g=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return s.log.error(b),n.errorHandler(o,s,b)}try{I=await m.onResponseSending(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}try{I=await $i(I,g,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,s,b)}s.dispatchEvent(new gt(o,I));try{await m.onResponseSendingFinal(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Fi(l,g,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return I}};function zu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(lr(t),{headers:{"content-type":"application/json"}})}i(zu,"resultToResponse");var Ne=class extends Le{static{i(this,"MetricsPlugin")}};var B=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new q(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var $=class{static{i(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{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(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var jt=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new $("ellie-metrics-transport",10,this.dispatchFunction,B.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:s}=w.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&s&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(s)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!u.ok){let c=await u.text();B.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var J=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=s,this.version=ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ft={name:"__system-no-version",pathPrefix:""};var ne=i(async(t,e,n,r)=>{let o=new Date,s=Date.now(),a=await r(t),u=t.headers.get(Ue)??void 0,c=t.headers.get(mi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof J&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.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:t.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:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new jt(e)),xe.forEach(I=>{if(I instanceof Ne){let b=I.getTransport();g.push(b)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var ve=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(ve||{});var dr=i((t,e)=>{let n=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return O.notFound(s,a);let l=w.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&B.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new K({processors:[ne],handler:n,gateway:e}),o=new J({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var pr=(E=>(E[E.CONTINUE=100]="CONTINUE",E[E.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",E[E.PROCESSING=102]="PROCESSING",E[E.EARLY_HINTS=103]="EARLY_HINTS",E[E.OK=200]="OK",E[E.CREATED=201]="CREATED",E[E.ACCEPTED=202]="ACCEPTED",E[E.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",E[E.NO_CONTENT=204]="NO_CONTENT",E[E.RESET_CONTENT=205]="RESET_CONTENT",E[E.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",E[E.MULTI_STATUS=207]="MULTI_STATUS",E[E.ALREADY_REPORTED=208]="ALREADY_REPORTED",E[E.IM_USED=226]="IM_USED",E[E.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",E[E.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",E[E.FOUND=302]="FOUND",E[E.SEE_OTHER=303]="SEE_OTHER",E[E.NOT_MODIFIED=304]="NOT_MODIFIED",E[E.USE_PROXY=305]="USE_PROXY",E[E.SWITCH_PROXY=306]="SWITCH_PROXY",E[E.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",E[E.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",E[E.BAD_REQUEST=400]="BAD_REQUEST",E[E.UNAUTHORIZED=401]="UNAUTHORIZED",E[E.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",E[E.FORBIDDEN=403]="FORBIDDEN",E[E.NOT_FOUND=404]="NOT_FOUND",E[E.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",E[E.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",E[E.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",E[E.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",E[E.CONFLICT=409]="CONFLICT",E[E.GONE=410]="GONE",E[E.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",E[E.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",E[E.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",E[E.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",E[E.URI_TOO_LONG=414]="URI_TOO_LONG",E[E.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",E[E.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",E[E.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",E[E.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",E[E.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",E[E.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",E[E.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",E[E.LOCKED=423]="LOCKED",E[E.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",E[E.TOO_EARLY=425]="TOO_EARLY",E[E.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",E[E.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",E[E.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",E[E.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",E[E.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",E[E.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",E[E.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",E[E.BAD_GATEWAY=502]="BAD_GATEWAY",E[E.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",E[E.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",E[E.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",E[E.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",E[E.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",E[E.LOOP_DETECTED=508]="LOOP_DETECTED",E[E.NOT_EXTENDED=510]="NOT_EXTENDED",E[E.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",E))(pr||{}),zi={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 ju={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"},mr=ju;function Vu(t){return`${new URL(t.url).pathname}`}i(Vu,"instance");function Gu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=t.headers.get(Ue);return r&&(n.rayId=r),n}i(Gu,"trace");var Wu=i((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Vu(e),trace:Gu(e,n),...r},additionalHeaders:o,statusText:mr[t.status]}),"merge"),gr=class{static{i(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?qe.format(e,n,r):qe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:zi[e],...n}}},O=class extends gr{static{i(this,"HttpProblems")}static#e(e,n,r,o,s){let a=Wu(this.getProblemFromStatus(e),n,r,o,s);return qe.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Ju}=Object.prototype,{propertyIsEnumerable:Ku}=Object.prototype;function fr(t){return Ju.call(t)}i(fr,"toString");function ae(t){return typeof t=="string"}i(ae,"isString");function Ke(t){return ae(t)&&t!==""}i(Ke,"isNonEmptyString");function ji(t){return fr(t)==="[object RegExp]"}i(ji,"isRegexp");function Vi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Ku.call(t,e))]}i(Vi,"getOwnEnumerableKeys");function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i($e,"isObject");function hr(t){return typeof t=="number"&&!isNaN(t)}i(hr,"isNumber");function yr(t){return t===!0||t===!1}i(yr,"isBoolean");function Gi(t){return typeof t>"u"}i(Gi,"isUndefined");function Wi(t){return Gi(t)||t===null}i(Wi,"isUndefinedOrNull");function ht(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(ht,"isErrorLike");var Ji=new Map;function Ye(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Ji.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){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 Ji.set(t,r),r}i(Ye,"statusCodesStringToNumberArray");function Fe(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(s=>{if(o===void 0)throw new A(`Error applying ${n} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Fe,"getValueFromRequestUser");function Be(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(ae(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(Be,"parseValueToStringArray");function Ki(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!$e(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ke(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!hr(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!yr(n.allowCredentials))throw new y("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=br(n,"allowedHeaders"),o=br(n,"allowedMethods"),s=br(n,"exposeHeaders"),a;try{a=Be(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.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 n.maxAge=="number"?n.maxAge.toString():void 0}})}i(Ki,"parseCorsPolicies");function br(t,e){let n;if(t[e]!==void 0)try{n=Be(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}i(br,"parseOptionalProperty");var Vt=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Gt=i((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var wr=i((t,e)=>{let n=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 O.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,c);if(!m)return O.notFound(a,u);let g=m.routeConfiguration,I=Yu(l,d,p,g,n);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),O.notFound(a,u))},"optionsHandler"),o=new K({processors:[ne],handler:r,gateway:e}),s=new J({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),Yu=i((t,e,n,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"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 y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Vt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Yi=i((t,e)=>{let n=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new K({processors:[ne],handler:n,gateway:e}),o=new J({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Rr=new J({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Qi=i((t,e)=>{let n=i(async(o,s)=>{let a=pt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return O.notFound(o,s)},"notFoundHandler"),r=new K({processors:[ne],handler:n,gateway:e});t.addRoute(Rr,r.execute)},"registerNotMatchedHandler");var Qu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xi=i(t=>{Qu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=i(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Xi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(t);if(!(s instanceof Response))throw new q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Xu(o,n.routeData.corsPolicies),u=ec(t,a),c=new Headers(s.headers);return Xi(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"),Xu=i((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),ec=i((t,e)=>{let n=Vt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var Pr=i((t,e)=>{let n=i(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new K({processors:[Wt],handler:n,gateway:e}),o=new J({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as es,trace as ts}from"@opentelemetry/api";var me={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 Jt=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,n){if(!ae(n))throw new A(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n,this.policyType=Object.getPrototypeOf(this).constructor.name}},Re=class extends Jt{static{i(this,"InboundPolicy")}},ke=class extends Jt{static{i(this,"OutboundPolicy")}};var Tr=class extends Re{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.policyType=e.name,this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},xr=class extends ke{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.policyType=e.name,this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},Er=new Map;function yt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(s=>!Er.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`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 y(`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 y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Re)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Tr(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Er.set(a.name,c)}),n.map(s=>{let a=Er.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(yt,"getInboundPolicyInstances");var Ir=new Map;function tc(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Ir.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ke)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new xr(a,s.handler.options??{},s.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Ir.set(s.name,u)}),n.map(o=>{let s=Ir.get(o);if(s===void 0)throw new A("Internal error. Policy not found in cache.");return s})}i(tc,"getOutboundPolicyInstances");var vr=i(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=ts.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...t],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,n);if(p instanceof Request||p instanceof z||p instanceof Response)return d.end(),p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:es.ERROR}),d.recordException(m),m}});if(l instanceof z)u=l;else if(l instanceof Request)u=new z(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),nc=i(t=>async(e,n,r)=>{let o=ts.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...t],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(me.PolicyName,c.policyName),d.setAttribute(me.PolicyType,c.policyType);let p=await c.handler(u,n,r);if(p instanceof Response)return p;{let m=new y(`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:es.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Kt=i(async(t,e,n,r)=>{let o=yt(e.route,n.routeData.policies),s=tc(e.route,n.routeData.policies);return rs({request:t,context:e,inboundPolicies:o,outboundPolicies:s,gateway:n,next:r})},"policyProcessor");function ns({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>rs({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ns,"createInternalPolicyProcessor");async function rs({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:s}){let a=vr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await s(u),l=nc(r),d;return w.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}i(rs,"executePolicyProcessor");function os(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||rc,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s);if(u===-1)u=t.length;else if(u<a){s=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(s,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=oc(l,o)}s=u+1}return n}i(os,"parse");function rc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}i(rc,"decode");function oc(t,e){try{return e(t)}catch{return t}}i(oc,"tryDecode");function is(t,e){try{let n=/v\d+(-\d+)?/g,o=os(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(is,"devPortalBaseURL");var ss="/__zuplo/dev-portal",ic="dev-portal-id",sc="dev-portal-host",ac="zp-account",uc="zp-project",cc="dev-portal-build",lc=`
43
43
  <!DOCTYPE html>
44
44
  <html lang="en">
45
45
  <head>
@@ -53,27 +53,27 @@ var Oa=Object.create;var Ln=Object.defineProperty;var Ca=Object.getOwnPropertyDe
53
53
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
54
54
  </body>
55
55
  </html>
56
- `,rs=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=w.instance.deploymentName,o=w.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(w.instance.isLocalDevelopment)return new Response(uc,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=ts(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:I,body:b}=c;return w.instance.build.ACCOUNT_NAME&&g.set(ic,w.instance.build.ACCOUNT_NAME),w.instance.build.PROJECT_NAME&&g.set(sc,w.instance.build.PROJECT_NAME),g.set(rc,r),g.set(oc,d.host),g.set(ac,w.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:I,body:b,redirect:"manual"})},"devPortalRoute"),a=new J({processors:[ne,Kt],handler:s,gateway:e}),u=new K({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),os=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(ns.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new J({processors:[ne],handler:r,gateway:e}),s=new K({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ns}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ds=Se(Ae());var Jt="system-logger",cc="api-key";var vr=0,yt=class{static{i(this,"CoreLogger")}constructor(e,n,r,o,s){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,s,a){vr>=Number.MAX_SAFE_INTEGER&&(vr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:vr++};this.#t[e](u,a)}};var Y=class extends Le{static{i(this,"LogPlugin")}};var Yt=class{static{i(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var bt=class{static{i(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var lc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),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}],Tr=Symbol(".toJSON was called"),mc=i(t=>{t[Tr]=!0;let e=t.toJSON();return delete t[Tr],e},"toJSON"),gc=i(t=>dc.get(t)??Error,"getErrorConstructor"),is=i(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&ft(t)){let l=gc(t.name);n=new l}else n={};if(e.push(t),s>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Tr]!==!0)return mc(t);let c=i(l=>is({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){s++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of pc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ft(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function oe(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?is({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(oe,"serializeError");var fc=/file:\/\/\/(.*?)\/dist\//g,hc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,yc="at async Event.respondWith";function ss(t){return typeof t!="string"?t:t.split(`
57
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(fc,"").replaceAll(hc,"").replaceAll(yc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
58
- `)}i(ss,"cleanStack");function Qt(t,e,n=""){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:`
56
+ `,as=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=w.instance.deploymentName,o=w.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(w.instance.isLocalDevelopment)return new Response(lc,{headers:{"content-type":"text/html"}});if(!r)return O.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=is(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:I,body:b}=c;return w.instance.build.ACCOUNT_NAME&&g.set(ac,w.instance.build.ACCOUNT_NAME),w.instance.build.PROJECT_NAME&&g.set(uc,w.instance.build.PROJECT_NAME),g.set(ic,r),g.set(sc,d.host),g.set(cc,w.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:I,body:b,redirect:"manual"})},"devPortalRoute"),a=new K({processors:[ne,Kt],handler:s,gateway:e}),u=new J({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),us=i((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(ss.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new K({processors:[ne],handler:r,gateway:e}),s=new J({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ss}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var fs=Se(_e());var Or=0,bt=class{static{i(this,"CoreLogger")}constructor(e,n,r,o,s){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,s,a){Or>=Number.MAX_SAFE_INTEGER&&(Or=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Or++};this.#t[e](u,a)}};var Y=class extends Le{static{i(this,"LogPlugin")}};var Yt=class{static{i(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var wt=class{static{i(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var dc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),pc=new Map(dc);var mc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Sr=Symbol(".toJSON was called"),gc=i(t=>{t[Sr]=!0;let e=t.toJSON();return delete t[Sr],e},"toJSON"),fc=i(t=>pc.get(t)??Error,"getErrorConstructor"),cs=i(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&ht(t)){let l=fc(t.name);n=new l}else n={};if(e.push(t),s>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Sr]!==!0)return gc(t);let c=i(l=>cs({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){s++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of mc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ht(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function oe(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?cs({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(oe,"serializeError");var hc=/file:\/\/\/(.*?)\/dist\//g,yc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,bc="at async Event.respondWith";function ls(t){return typeof t!="string"?t:t.split(`
57
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(hc,"").replaceAll(yc,"").replaceAll(bc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
58
+ `)}i(ls,"cleanStack");function Qt(t,e,n=""){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:`
59
59
  `,newlineOrSpace:`
60
60
  `,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 m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
61
- `).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"||$i(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 g="["+p.newline+a.map((I,b)=>{let x=a.length-1===b?p.newline:","+p.newlineOrSpace,L=s(I,u,c+d,l+1);return u.transform&&(L=u.transform(a,b,L)),p.indent+L+x}).join("")+p.pad+"]";return r.pop(),m(g)}if(qe(a)){let g=Fi(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((b,x)=>{let L=g.length-1===x?p.newline:","+p.newlineOrSpace,f=typeof b=="symbol",P=!f&&/^[a-z$_][$\w]*$/i.test(b),O=f||P?b:s(b,u,"",l+1),H=s(a[b],u,c+d,l+1);return u.transform&&(H=u.transform(a,b,H)),p.indent+String(O)+": "+H+L}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
62
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Qt,"stringifyObject");function ke(t){return t.map(e=>oe(e))}i(ke,"makeErrorsSerializable");function Je(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:Te(oe(e))}i(Je,"extractBestMessage");function as(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ft(n))if(n.stack)e.push(n.stack);else{let r=Qt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Qt(n);e.push(r)}else{let r=Sr(n);e.push(r)}}),e.join(`
63
- `)}i(as,"messagesToMultilineText");function Te(t){return typeof t=="string"?t:JSON.stringify(t)}i(Te,"stringifyNonString");function Sr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?mr(t):"unknown"}i(Sr,"stringifyNonStringToText");import{importPKCS8 as bc,SignJWT as wc}from"jose";async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t?.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,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function Re({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new wc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(Re,"getTokenFromGcpServiceAccount");async function us(t,e,n){return cs(t,{token:e,returnSecureToken:!0},n)}i(us,"exchangeFirebaseJwtForIdToken");async function Xt(t,e,n){return cs(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(Xt,"exchangeGgpJwtForIdToken");async function cs(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(cs,"fetchToken");var ue=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await bc(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 Or=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new wt(this.options)}},Rc="https://logging.googleapis.com/v2/entries:write?alt=json",Cr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},wt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ue.init(this.#e)}log(e,n){if(!this.#t)throw new q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ke(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Cr[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=Je(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ue.init(this.#e));let n=await Re({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Rc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new $("google-log-transport",1,this.dispatchFunction)};var en="gcp";function tn(t){let e={allMessages:ke(t.messages)},n="zuplo-production",r=Je(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:Cr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(tn,"gcpLogFormat");var Rt=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===en){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,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Nr=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Pt(this.options)}},Ar="__ddtags",Lr="__ddattr",_r=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Pc=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(_r(r)):n.push(`${_r(r)}:${_r(o.toString())}`)}),n.join(",")},"formatTags"),Pt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[Ar];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Ar]!==void 0);a>-1&&(Object.assign(r,s[a][Ar]),s.splice(a,1));let u={},c=n.custom[Lr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Lr]!==void 0);l>-1&&(Object.assign(u,s[l][Lr]),s.splice(l,1));let d=ke(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Je(d),service:e.loggingId,ddtags:Pc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var Et=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===en){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 Ec=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:ke(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),nn,rn=class{static{i(this,"RemoteLogTransport")}constructor(e){nn||(nn=new $("remote-log-transport",1,Ec(e)))}log(e,n){nn.enqueue(e),n.waitUntil(nn.waitUntilFlushed())}};var Ic={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ls=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:Ic[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var xc=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=ls(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),on,sn=class{static{i(this,"UnifiedLogTransport")}constructor(e){on||(on=new $("unified-log-transport",1,xc(e)))}async log(e,n){on.enqueue(e),n.waitUntil(on.waitUntilFlushed())}};var kr=(0,ds.debug)("zuplo:logging"),an=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(w.instance,e),r=await t.setupUserCoreLogger(w.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;kr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(Jt);return s?o.push(new Et(s.logger,e.logFormat)):e.isDeno&&o.push(new Rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new sn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new yt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){kr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(Jt);if(a&&a.captureUserLogs===!0?r.push(new Et(a.logger,e.logFormat)):e.isDeno&&r.push(new Rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new rn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new wt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Pt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return xe.forEach(u=>{u instanceof Y&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new yt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){kr("Gateway.createRequestLoggers");let a=new Yt(r,o,s),u=new bt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new bt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Be=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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Mr=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},It=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Dr=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},xt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Be||e instanceof K))throw new q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Mr(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Dr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:n});if(u!==null)return new It(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new It(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Hr;function ps(t){Hr=t}i(ps,"setGlobalZuploEventContext");function un(){if(Hr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Hr}i(un,"getGlobalZuploEventContext");function ms({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:n}){let r=new Headers(t);if(e){for(let[o]of t){let s=o.substring(0,3);di.includes(s.toLowerCase())&&!pi.includes(o.toLowerCase())&&r.delete(o)}r.delete(Qo)}else li.forEach(o=>{r.delete(o)});return n&&mi.forEach(o=>{r.delete(o)}),r}i(ms,"normalizeIncomingRequestHeaders");var Pe=(0,fs.debug)("zuplo:runtime"),vc=i(t=>{let e=t.findIndex(n=>n.name===gt.name);return e>-1?[...t.splice(e),gt]:[...t,gt]},"setupSystemNoVersion"),X=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Pe("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o){if(Pe("Gateway.initialize"),t.#e||await gs.getTracer("gateway").startActiveSpan("gateway:initialize",async a=>{try{let u=await an.init(r),c=e(),l={...c,corsPolicies:Vi(c.corsPolicies)},d=new t(l,n,u,o);t.#e=d}finally{a.end()}}),!t.#e)throw new q("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){Pe("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new q("Gateway cannot be used before it is initialized");return t.#e}#t;#n;#r=[Kt,Gt,ne];#o;setupRoutes=()=>{Pe("Gateway.setupRoutes");let e=this.routeData,n=vc(e.versions),r=new xt(n);if(e.routes.length===0)return cr(r,this),wr(r,this),yr(r,this),Gi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(os(r,this),rs(r,this)),cr(r,this),wr(r,this),yr(r,this);for(let s of xe)s instanceof Ie&&s.registerRoutes(r,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 y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new Be(s);r.addRoute(c,u.execute)}),Wi(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Pe("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Pe("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=ss(s.stack)),o={cause:s}}}return T.internalServerError(e,n,{detail:r.message,...o})}async handleRequest(e,n,r){let{requestId:o,rayId:s}=n;ps(r);let a=ms({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:w.instance.isDeno});a.set(De,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let f=new Headers(u.headers);f.set(kn,"true"),u=new Request(u,{headers:f,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new cn(e.headers),b=new z(u,{params:g.params}),x=new ln({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I});gs.getActiveSpan()?.setAttributes({"http.route":x.route.pathPattern??x.route.path,"cloud.region":x.incomingRequestProperties.colo});let L=te.initialize(x,b);if(g.routeConfiguration===br&&lt.value?.notFoundHandler!==void 0){let f=this.#n.lookupByPathOnly(m);L.pathOnlyMatches=f.map(P=>P.routeConfiguration).filter(P=>P instanceof Be)}try{if(B.addLogger(x,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let H=await Di(b,x);if(H instanceof Response)return H;{let h=te.getContextExtensions(x);b=H,h.latestRequest=b}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let f=g.executableHandler;Tc(f,g,u),Pe("Gateway.handleRequest - call user handler");let P=await f(b,x);if(Pe("Gateway.handleRequest - user handler"),!(P instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof P}`);if(P.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let O;if(P.headers.get(De)===null&&!P.webSocket){let H=new Headers(P.headers);H.set(De,o),O=new Response(P.body,{status:P.status,statusText:P.statusText,headers:H,cf:P.cf})}else O=P;return O}catch(f){return Pe("Gateway - error executing handler",f),f instanceof A?(l.error(f),d.warn(f)):d.error(f),await this.#i(b,x,f)}}};function Tc(t,e,n){if(Pe("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(Tc,"checkHandler");var hs=i(async(t,e,n)=>{let r=X.instance.routeData.policies,o=ht([t],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var cn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(qn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get($n)??void 0}get city(){return this.#e.get(Mn)??this.#e.get(oi)??void 0}get continent(){return this.#e.get(Dn)??this.#e.get(ii)??void 0}get country(){return this.#e.get(Hn)??this.#e.get(si)??void 0}get latitude(){return this.#e.get(Zn)??this.#e.get(ui)??void 0}get longitude(){return this.#e.get(Un)??this.#e.get(ai)??void 0}get colo(){return this.#e.get(Fn)??void 0}get postalCode(){return this.#e.get(ni)??this.#e.get(Bn)??void 0}get metroCode(){return this.#e.get(ti)??this.#e.get(zn)??void 0}get region(){return this.#e.get(Xo)??this.#e.get(jn)??void 0}get regionCode(){return this.#e.get(ei)??this.#e.get(Vn)??void 0}get timezone(){return this.#e.get(ri)??this.#e.get(Gn)??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}}},pt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},ln=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>hs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.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 me=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Sc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ys(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Sc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(ys,"isRestrictedEnvVariableName");function bs(t){return!!t.startsWith("ZUPLO_")}i(bs,"isZuploReadableEnvVariableName");var se=new Proxy({},{get(t,e){if(!(ys(String(e))&&!bs(String(e))))return w.instance.runtime[String(e)]}});var Rs=Se(Ae());var ge=(0,Rs.debug)("zuplo:runtime:external-service");function Ps(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(Ps,"getServiceAuth");async function Es(t){let e=Ps();if(!e)throw ge("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.");if(typeof t!="string")throw ge("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(w.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let a=w.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await xs(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(Es,"externalServiceTunnelConfig");async function Is(t,e){let n=Ps();if(n)if(ge(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(w.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await xs(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);ge(`Calling external service: ${c.toString()}`);let l=await vt(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw ge("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw ge("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(Is,"externalServiceHandler");async function xs(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=Oc(r);ge(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ws(`${s}-${o}`),l=await ws(`${s}-${a}-${u}`);return`${c}.${l}`}i(xs,"hashServiceName");async function ws(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(ws,"hashSegment");function Oc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Oc,"sanitizeEnvironmentType");var vs=new Map;vs.set("service:",Is);var vt=globalThis.fetch;globalThis.fetch=function(t,e){let n=Cc(e);if(typeof t=="string"){let r=new URL(t),o=vs.get(r.protocol);return o?o(t,n):vt(t,n)}else return vt(t,n)};var Cc=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");import{AsyncLocalStorage as Ac}from"node:async_hooks";var Ts={request:new Ac};var Lc=i(()=>{X.purgeGatewayCache()},"purgeGatewayCache"),_c="Error initializing gateway. Check your configuration for errors or contact support.",Nc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Ur=class{constructor(e,n,r,o,s,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,n,r)=>{let o=e.headers.get(De)??e.headers.get(Yo)??crypto.randomUUID(),s=e.headers.get(He),a={requestId:o,rayId:s};return Ts.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:n});try{await Zi(this.runtimeInit)}catch(c){this.handleError(c,Nc,e)}return ki(i(async(c,l)=>{let d;try{d=await X.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,_c,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,n,r){console.error("Error initializing gateway.",e),e instanceof y&&(n=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:n,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ms=Se(Ae());function kc(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(kc,"lexer");function Zr(t,e){e===void 0&&(e={});for(var n=kc(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Dc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(h){if(c<n.length&&n[c].type===h)return n[c++].value},"tryConsume"),p=i(function(h){var R=d(h);if(R!==void 0)return R;var S=n[c],M=S.type,C=S.index;throw new TypeError("Unexpected ".concat(M," at ").concat(C,", expected ").concat(h))},"mustConsume"),m=i(function(){for(var h="",R;R=d("CHAR")||d("ESCAPED_CHAR");)h+=R;return h},"consumeText");c<n.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var x=g||"";o.indexOf(x)===-1&&(l+=x,x=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:x,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var L=g||d("ESCAPED_CHAR");if(L){l+=L;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var x=m(),P=d("NAME")||"",O=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(O?u++:""),pattern:P&&!O?s:O,prefix:x,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Zr,"parse");function Ss(t,e){return Mc(Zr(t,e),e)}i(Ss,"compile");function Mc(t,e){e===void 0&&(e={});var n=Hc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var x=o(m[b],p);if(a&&!u[d].test(x))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var x=o(String(m),p);if(a&&!u[d].test(x))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(x,'"'));l+=p.prefix+x+p.suffix;continue}if(!g){var L=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(Mc,"tokensToFunction");function Dc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Dc,"escapeString");function Hc(t){return t&&t.sensitive?"":"i"}i(Hc,"flags");var Ls=Se(Ae());var Uc=(0,Ls.debug)("zuplo:runtime"),$r=new TextEncoder,Os={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"},Zc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Ye=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,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,n){let r=new Fr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Uc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=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 y("An unknown error occurred, ensure retries is not negative")}},Fr=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:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(n==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let x,L;(!c||!l)&&([x,L]=qc(this.url,this.headers)),this.service=c||x||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let f=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"),f.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&f.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(O=>I||!Zc.includes(O)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(O=>O+":"+(O==="host"?this.url.host:(this.headers.get(O)||"").replace(/\s+/g," "))).join(`
64
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!f.has("X-Amz-Expires")&&f.set("X-Amz-Expires","86400"),f.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),f.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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=As(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([O])=>{if(!O)return!1;if(this.service==="s3"){if(P.has(O))return!1;P.add(O)}return!0}).map(O=>O.map(H=>As(encodeURIComponent(H)))).sort(([O,H],[h,R])=>O<h?-1:O>h?1:H<R?-1:H>R?1:0).map(O=>O.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await Tt("AWS4"+this.secretAccessKey,e),s=await Tt(o,this.region),a=await Tt(s,this.service);r=await Tt(a,"aws4_request"),this.cache.set(n,r)}return qr(await Tt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,qr(await Cs(await this.canonicalString()))].join(`
61
+ `).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"||ji(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 g="["+p.newline+a.map((I,b)=>{let T=a.length-1===b?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,b,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if($e(a)){let g=Vi(a);if(u.filter&&(g=g.filter(b=>u.filter?.(a,b))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((b,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof b=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(b),v=h||P?b:s(b,u,"",l+1),H=s(a[b],u,c+d,l+1);return u.transform&&(H=u.transform(a,b,H)),p.indent+String(v)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
62
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Qt,"stringifyObject");function Me(t){return t.map(e=>oe(e))}i(Me,"makeErrorsSerializable");function Qe(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:Oe(oe(e))}i(Qe,"extractBestMessage");function ds(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ht(n))if(n.stack)e.push(n.stack);else{let r=Qt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Qt(n);e.push(r)}else{let r=Cr(n);e.push(r)}}),e.join(`
63
+ `)}i(ds,"messagesToMultilineText");function Oe(t){return typeof t=="string"?t:JSON.stringify(t)}i(Oe,"stringifyNonString");function Cr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?fr(t):"unknown"}i(Cr,"stringifyNonStringToText");import{importPKCS8 as wc,SignJWT as Rc}from"jose";async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t?.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,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function Pe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new Rc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(Pe,"getTokenFromGcpServiceAccount");async function ps(t,e,n){return ms(t,{token:e,returnSecureToken:!0},n)}i(ps,"exchangeFirebaseJwtForIdToken");async function Xt(t,e,n){return ms(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(Xt,"exchangeGgpJwtForIdToken");async function ms(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ms,"fetchToken");var ue=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await wc(n.private_key.trim(),"RS256");return new t({serviceAccount:n,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 Ar=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Rt(this.options)}},Pc="https://logging.googleapis.com/v2/entries:write?alt=json",_r={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Rt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ue.init(this.#e)}log(e,n){if(!this.#t)throw new q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:_r[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=Qe(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ue.init(this.#e));let n=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Pc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new $("google-log-transport",1,this.dispatchFunction)};var en="gcp";function tn(t){let e={allMessages:Me(t.messages)},n="zuplo-production",r=Qe(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:_r[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(tn,"gcpLogFormat");var Pt=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===en){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,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Mr=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Et(this.options)}},Lr="__ddtags",Nr="__ddattr",kr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ec=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(kr(r)):n.push(`${kr(r)}:${kr(o.toString())}`)}),n.join(",")},"formatTags"),Et=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[Lr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Lr]!==void 0);a>-1&&(Object.assign(r,s[a][Lr]),s.splice(a,1));let u={},c=n.custom[Nr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Nr]!==void 0);l>-1&&(Object.assign(u,s[l][Nr]),s.splice(l,1));let d=Me(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Qe(d),service:e.loggingId,ddtags:Ec(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var It=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===en){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 Ic=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),nn,rn=class{static{i(this,"RemoteLogTransport")}constructor(e){nn||(nn=new $("remote-log-transport",1,Ic(e)))}log(e,n){nn.enqueue(e),n.waitUntil(nn.waitUntilFlushed())}};var Tc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},gs=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:Tc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var xc=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=gs(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),on,sn=class{static{i(this,"UnifiedLogTransport")}constructor(e){on||(on=new $("unified-log-transport",1,xc(e)))}async log(e,n){on.enqueue(e),n.waitUntil(on.waitUntilFlushed())}};var Dr=(0,fs.debug)("zuplo:logging"),an=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(w.instance,e),r=await t.setupUserCoreLogger(w.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Dr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(kt);return s?o.push(new It(s.logger,e.logFormat)):e.isDeno&&o.push(new Pt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new sn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new bt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Dr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(kt);if(a&&a.captureUserLogs===!0?r.push(new It(a.logger,e.logFormat)):e.isDeno&&r.push(new Pt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new rn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Rt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Et({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return xe.forEach(u=>{u instanceof Y&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new bt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){Dr("Gateway.createRequestLoggers");let a=new Yt(r,o,s),u=new wt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new wt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ze=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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Hr=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Tt=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Ur=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},xt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ze||e instanceof J))throw new q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Hr(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ur(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:n});if(u!==null)return new Tt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Tt(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Zr;function hs(t){Zr=t}i(hs,"setGlobalZuploEventContext");function un(){if(Zr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Zr}i(un,"getGlobalZuploEventContext");function ys({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:n}){let r=new Headers(t);if(e){for(let[o]of t){let s=o.substring(0,3);fi.includes(s.toLowerCase())&&!hi.includes(o.toLowerCase())&&r.delete(o)}r.delete(ni)}else gi.forEach(o=>{r.delete(o)});return n&&yi.forEach(o=>{r.delete(o)}),r}i(ys,"normalizeIncomingRequestHeaders");var Ee=(0,ws.debug)("zuplo:runtime"),vc=i(t=>{let e=t.findIndex(n=>n.name===ft.name);return e>-1?[...t.splice(e),ft]:[...t,ft]},"setupSystemNoVersion"),ee=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Ee("Gateway.constructor"),me,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o){if(Ee("Gateway.initialize"),t.#e||await bs.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[me.SystemTrace]:!0}},async a=>{try{let u=await an.init(r),c=e(),l={...c,corsPolicies:Ki(c.corsPolicies)},d=new t(l,n,u,o);t.#e=d}finally{a.end()}}),!t.#e)throw new q("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new q("Gateway cannot be used before it is initialized");return t.#e}#t;#n;#r=[Kt,Wt,ne];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,n=vc(e.versions),r=new xt(n);if(e.routes.length===0)return dr(r,this),Pr(r,this),wr(r,this),Yi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(us(r,this),as(r,this)),dr(r,this),Pr(r,this),wr(r,this);for(let s of xe)s instanceof Te&&s.registerRoutes(r,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 y(`Invalid state - No handler on route for path '${s.path}'`);let u=new K({processors:this.#r,handler:a,gateway:this}),c=new ze(s);r.addRoute(c,u.execute)}),Qi(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Ee("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Ee("Gateway.internalErrorResponse");let o={};if(w.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=ls(s.stack)),o={cause:s}}}return O.internalServerError(e,n,{detail:r.message,...o})}async handleRequest(e,n,r){let{requestId:o,rayId:s}=n;hs(r);let a=ys({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:w.instance.isDeno});a.set(He,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Dn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new cn(e.headers),b=new z(u,{params:g.params}),T=new ln({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();bs.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[me.RoutePathPattern]:T.route.pathPattern,[me.RouteOperationId]:_.operationId,[me.RouteTrace]:_["x-zuplo-trace"],[me.RouteSystem]:Je(p)?!0:void 0});let h=te.initialize(T,b);if(g.routeConfiguration===Rr&&pt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(v=>v.routeConfiguration).filter(v=>v instanceof ze)}try{if(B.addLogger(T,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Je(p):!p.pathname.startsWith("/__zuplo")){let f=await qi(b,T);if(f instanceof Response)return f;{let R=te.getContextExtensions(T);b=f,R.latestRequest=b}}Je(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Oc(P,g,u),Ee("Gateway.handleRequest - call user handler");let v=await P(b,T);if(Ee("Gateway.handleRequest - user handler"),!(v instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof v}`);if(v.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(v.headers.get(He)===null&&!v.webSocket){let f=new Headers(v.headers);f.set(He,o),H=new Response(v.body,{status:v.status,statusText:v.statusText,headers:f,cf:v.cf})}else H=v;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(b,T,P)}}};function Oc(t,e,n){if(Ee("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(Oc,"checkHandler");var Rs=i(async(t,e,n)=>{let r=ee.instance.routeData.policies,o=yt([t],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var cn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Fn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Bn)??void 0}get city(){return this.#e.get(Hn)??this.#e.get(ui)??void 0}get continent(){return this.#e.get(Un)??this.#e.get(ci)??void 0}get country(){return this.#e.get(Zn)??this.#e.get(li)??void 0}get latitude(){return this.#e.get($n)??this.#e.get(pi)??void 0}get longitude(){return this.#e.get(qn)??this.#e.get(di)??void 0}get colo(){return this.#e.get(zn)??void 0}get postalCode(){return this.#e.get(si)??this.#e.get(jn)??void 0}get metroCode(){return this.#e.get(ii)??this.#e.get(Vn)??void 0}get region(){return this.#e.get(ri)??this.#e.get(Gn)??void 0}get regionCode(){return this.#e.get(oi)??this.#e.get(Wn)??void 0}get timezone(){return this.#e.get(ai)??this.#e.get(Jn)??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}}},mt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},gt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},ln=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Rs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.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 ge=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Sc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Cc(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Sc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(Cc,"isRestrictedEnvVariableName");function Ac(t){return!!t.startsWith("ZUPLO_")}i(Ac,"isZuploReadableEnvVariableName");var se=new Proxy({},{get(t,e){if(!(Cc(String(e))&&!Ac(String(e))))return w.instance.runtime[String(e)]}});import{AsyncLocalStorage as _c}from"node:async_hooks";var Ps={request:new _c};var Lc="Error initializing gateway. Check your configuration for errors or contact support.",Nc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",qr=class{constructor(e,n,r,o,s,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,n,r)=>{let o=e.headers.get(He)??e.headers.get(ti)??crypto.randomUUID(),s=e.headers.get(Ue),a={requestId:o,rayId:s};return Ps.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:n});try{await Bi(this.runtimeInit)}catch(c){this.handleError(c,Nc,e)}return Ui(i(async(c,l)=>{let d;try{d=await ee.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Lc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,n,r){console.error("Error initializing gateway.",e),e instanceof y&&(n=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:n,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var As=Se(_e());function kc(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(kc,"lexer");function $r(t,e){e===void 0&&(e={});for(var n=kc(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Dc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<n.length&&n[c].type===f)return n[c++].value},"tryConsume"),p=i(function(f){var R=d(f);if(R!==void 0)return R;var S=n[c],M=S.type,C=S.index;throw new TypeError("Unexpected ".concat(M," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",R;R=d("CHAR")||d("ESCAPED_CHAR");)f+=R;return f},"consumeText");c<n.length;){var g=d("CHAR"),I=d("NAME"),b=d("PATTERN");if(I||b){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",v=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(v?u++:""),pattern:P&&!v?s:v,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i($r,"parse");function Es(t,e){return Mc($r(t,e),e)}i(Es,"compile");function Mc(t,e){e===void 0&&(e={});var n=Hc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var T=o(m[b],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(Mc,"tokensToFunction");function Dc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Dc,"escapeString");function Hc(t){return t&&t.sensitive?"":"i"}i(Hc,"flags");var vs=Se(_e());var Uc=(0,vs.debug)("zuplo:runtime"),Br=new TextEncoder,Is={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"},Zc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Xe=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,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,n){let r=new zr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Uc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=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 y("An unknown error occurred, ensure retries is not negative")}},zr=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:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:b}){if(n==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=qc(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(v=>I||!Zc.includes(v)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(v=>v+":"+(v==="host"?this.url.host:(this.headers.get(v)||"").replace(/\s+/g," "))).join(`
64
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=xs(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([v])=>{if(!v)return!1;if(this.service==="s3"){if(P.has(v))return!1;P.add(v)}return!0}).map(v=>v.map(H=>xs(encodeURIComponent(H)))).sort(([v,H],[f,R])=>v<f?-1:v>f?1:H<R?-1:H>R?1:0).map(v=>v.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await vt("AWS4"+this.secretAccessKey,e),s=await vt(o,this.region),a=await vt(s,this.service);r=await vt(a,"aws4_request"),this.cache.set(n,r)}return Fr(await vt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fr(await Ts(await this.canonicalString()))].join(`
65
65
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
66
66
  `,this.signedHeaders,await this.hexBodyHash()].join(`
67
- `)}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 A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=qr(await Cs(this.body||""))}return e}};async function Tt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?$r.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,$r.encode(e))}i(Tt,"hmac");async function Cs(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?$r.encode(t):t)}i(Cs,"hash");function qr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(qr,"buf2hex");function As(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(As,"encodeRfc3986");function qc(t,e){let{hostname:n,pathname:r}=t,o=n.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")n.startsWith("iot.")?s="execute-api":n.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 Os?[Os[s],a]:[s,a]}i(qc,"guessServiceRegion");function $c(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i($c,"b64ToUint6");function _s(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.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|=$c(n.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(_s,"base64Decode");function dn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(dn,"uint6ToB64");function Ns(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(dn(o>>>18&63),dn(o>>>12&63),dn(o>>>6&63),dn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ns,"base64Encode");function Qe(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(Qe,"numberToString");function Fc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Qe(Math.floor(n/60)),s=Qe(n%60);return`${r}${o}${s}`}i(Fc,"getCLFOffset");function Br(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=Qe(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=Qe(t.getHours()),a=Qe(t.getMinutes()),u=Qe(t.getSeconds()),c=Fc(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Br,"toCLFDate");var ks=(0,Ms.debug)("zuplo:runtime"),Bc="X-Amzn-Trace-Id",zc="x-amzn-errortype",Ds=[],jc=i(async(t,e,n)=>{let r=n;for await(let o of Ds)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ce=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Bc)??void 0,this.errorType=n.get(zc)??void 0}},Vc={addSendingAwsLambdaEventHook:t=>{Ds.push(t)}};async function Gc(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Ye({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ks(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await Yc(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=Jc(t,e):I=await Kc(t,e,{useAwsResourcePathStyle:u}),ks("Calling onSendingAwsLambdaEvent hook");let b=await jc(t,e,I);b.body=p,b.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(b)});try{return Wc(x)}catch(L){if(L instanceof ce){let f=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&L.traceId?{AMZN_TRACE_ID_HEADER:L.traceId}:void 0;return T.internalServerError(t,e,void 0,f)}throw L}}i(Gc,"awsLambdaHandler");async function Wc(t){let e;try{e=await t.json()}catch{throw new ce("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ce(e.message,t.headers):new ce(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ce(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ce(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ce(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ce(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ce("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ce("Response was set to base64 encoded but body was not a string",t.headers);r=_s(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 ce(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(Wc,"getResponse");async function Kc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.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:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.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:Br(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Xc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(Kc,"buildEventVersion1");function Jc(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.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:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Br(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(Jc,"buildEventVersion2");async function Yc(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Qc(e,o)){let s=await t.arrayBuffer();n=Ns(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(Yc,"getBodyResult");function Qc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(Qc,"matchesContentType");function Xc(t,e=!1){if(!e)return t;let n=Zr(t),r=Ss(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Xc,"getResourcePath");var el=[502,503,504];async function Xe(t,e){if(el.includes(t.status)){let n=B.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(Xe,"logBadGatewayResponses");var zr;function Me(t){if(zr===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),zr=n}return t.log[zr]}i(Me,"getHandlerUserLogFunction");async function tl(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=nl(s);if(!a.isValid)throw new y(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return T.notFound(t,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 Xe(l,e),l}i(tl,"openApiSpecHandler");var nl=i(t=>t.startsWith("./")?t.startsWith("./config")?t.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 rl(t,e){let n=e.route.handler.options;if(!n.location)throw new y("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(rl,"redirectHandler");function ol(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(ol,"join");async function il(t,e){let n=Me(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 y("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=ol(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),Xe(p,e),p}i(il,"urlForwardHandler");var sl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function al(t,e){let n=Me(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?sl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Xe(d,e),d}i(al,"urlRewriteHandler");async function ul(t,e){let n=w.instance,r=e.route.handler.options,o=Me(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await Es(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let x in g.tunnelHeaders)p.set(x,g.tunnelHeaders[x])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(ul,"webSocketHandler");var jr=i((t,e)=>t.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 y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Hs=i(async(t,e,n,r,o,s)=>{let a=t.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,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Us(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Hs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Us,"wireUpListeners");async function cl(t,e){let n=w.instance,r=e.route.handler.options,o=Me(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new y("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let L=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${L}'`;throw new Error(f)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let b=r.policies&&r.policies.inbound?jr(r.policies.inbound,"inbound"):[],x=r.policies&&r.policies.outbound?jr(r.policies.outbound,"outbound"):[];return Us(m,I,t,e,b),Us(I,m,t,e,x),new Response(null,{status:101,webSocket:p})}i(cl,"webSocketPipelineHandler");var Vr=class extends Y{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Gr(this.options)}},Gr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Te(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new $("dyna-trace-log-transport",10,this.#i)};var Wr=class extends Y{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Jr(this.options)}},Kr=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function ll(t,e){return btoa(`${t}:${e}`)}i(ll,"createBasicDigest");var Jr=class{static{i(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=ll(e.username,e.password),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Kr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let s={stream:r,message:Te(oe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new $("loki-log-transport",10,this.#s)};var Yr=class extends Y{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Qr(this.options)}},Qr=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Te(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
68
- `),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),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new $("sumo-logic-log-transport",10,this.#s)};var dl="d3a5b78f823648f5b1df4fe269d41172",Xr=class extends Y{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??dl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.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,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=as(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),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=Sr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let n=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new $("vmware-log-insights-log-transport",10,this.#a)};var to=class extends Y{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new no(this.options)}},no=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new $("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new Ye({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Te(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var ro=new WeakMap,pl={tags:[]},oo=class extends _e{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new io(this.options)}static setContext(n,r){let o=ro.get(n);o||(o=pl);let s=Object.assign({...o},r);ro.set(n,s)}},io=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,n){this.#i===void 0&&(this.#i=new $("data-dog-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(ro.get(n)?.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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new so(await r.text())}},so=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var ao=new WeakMap,ml={dimensions:[]},uo=class extends _e{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new co(this.options)}static setContext(n,r){let o=ao.get(n);o||(o=ml);let s=Object.assign({...o},r);ao.set(n,s)}},co=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,n){this.#r===void 0&&(this.#r=new $("dynatrace-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(ao.get(n)?.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}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
69
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new lo(await r.text())}},lo=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var po=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var mo=class extends Ie{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new go(e,this.#e,this.#t)}},Zs=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),gl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},go=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...gl};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 $("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Zs(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Zs(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)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(m=>{n.log.error(m)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var fo=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}},Ee=class extends fo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var fl="v1",hl=300;async function qs(t,e,n,r=hl,o){return await bl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(qs,"constructEventAsync");function yl(t,e){return`${e.timestamp}.${t}`}i(yl,"makeHMACContent");async function bl(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=wl(t,e,fl),l=/\s/.test(n),d=await Il(yl(a,u),n);return Rl(a,s,u,d,r,c,l,o)}i(bl,"verifyHeaderAsync");function wl(t,e,n){if(!t)throw new Ee(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;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 Ee(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Pl(a,n);if(!u||u.timestamp===-1)throw new Ee(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ee(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(wl,"parseEventDetails");function Rl(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(m=>El(m,r)).length,l=`
67
+ `)}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 A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fr(await Ts(this.body||""))}return e}};async function vt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Br.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Br.encode(e))}i(vt,"hmac");async function Ts(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Br.encode(t):t)}i(Ts,"hash");function Fr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Fr,"buf2hex");function xs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(xs,"encodeRfc3986");function qc(t,e){let{hostname:n,pathname:r}=t,o=n.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")n.startsWith("iot.")?s="execute-api":n.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 Is?[Is[s],a]:[s,a]}i(qc,"guessServiceRegion");function $c(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i($c,"b64ToUint6");function Os(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.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|=$c(n.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(Os,"base64Decode");function dn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(dn,"uint6ToB64");function Ss(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(dn(o>>>18&63),dn(o>>>12&63),dn(o>>>6&63),dn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ss,"base64Encode");function et(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(et,"numberToString");function Fc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=et(Math.floor(n/60)),s=et(n%60);return`${r}${o}${s}`}i(Fc,"getCLFOffset");function jr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=et(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=et(t.getHours()),a=et(t.getMinutes()),u=et(t.getSeconds()),c=Fc(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(jr,"toCLFDate");var Cs=(0,As.debug)("zuplo:runtime"),Bc="X-Amzn-Trace-Id",zc="x-amzn-errortype",_s=[],jc=i(async(t,e,n)=>{let r=n;for await(let o of _s)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ce=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Bc)??void 0,this.errorType=n.get(zc)??void 0}},Vc={addSendingAwsLambdaEventHook:t=>{_s.push(t)}};async function Gc(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Xe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Cs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await Yc(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=Kc(t,e):I=await Jc(t,e,{useAwsResourcePathStyle:u}),Cs("Calling onSendingAwsLambdaEvent hook");let b=await jc(t,e,I);b.body=p,b.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(b)});try{return Wc(T)}catch(_){if(_ instanceof ce){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return O.internalServerError(t,e,void 0,h)}throw _}}i(Gc,"awsLambdaHandler");async function Wc(t){let e;try{e=await t.json()}catch{throw new ce("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ce(e.message,t.headers):new ce(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ce(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ce(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ce(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ce(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ce("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ce("Response was set to base64 encoded but body was not a string",t.headers);r=Os(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 ce(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(Wc,"getResponse");async function Jc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.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:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.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:jr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Xc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(Jc,"buildEventVersion1");function Kc(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.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:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:jr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(Kc,"buildEventVersion2");async function Yc(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Qc(e,o)){let s=await t.arrayBuffer();n=Ss(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(Yc,"getBodyResult");function Qc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(Qc,"matchesContentType");function Xc(t,e=!1){if(!e)return t;let n=$r(t),r=Es(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Xc,"getResourcePath");var el=[502,503,504];async function tt(t,e){if(el.includes(t.status)){let n=B.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(tt,"logBadGatewayResponses");var Vr;function De(t){if(Vr===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Vr=n}return t.log[Vr]}i(De,"getHandlerUserLogFunction");async function tl(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=nl(s);if(!a.isValid)throw new y(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return O.notFound(t,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 tt(l,e),l}i(tl,"openApiSpecHandler");var nl=i(t=>t.startsWith("./")?t.startsWith("./config")?t.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 rl(t,e){let n=e.route.handler.options;if(!n.location)throw new y("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(rl,"redirectHandler");function ol(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(ol,"join");async function il(t,e){let n=De(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 y("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=ol(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),tt(p,e),p}i(il,"urlForwardHandler");var sl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function al(t,e){let n=De(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?sl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),tt(d,e),d}i(al,"urlRewriteHandler");var Ms=Se(_e());var Ls=new Map;Ls.set("service:",Ns);var pn=globalThis.fetch;globalThis.fetch=function(t,e){let n=ul(e);if(typeof t=="string"){let r=new URL(t),o=Ls.get(r.protocol);return o?o(t,n):pn(t,n)}else return pn(t,n)};var ul=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var fe=(0,Ms.debug)("zuplo:runtime:external-service");function Ds(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=w.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(Ds,"getServiceAuth");async function Hs(t){let e=Ds();if(!e)throw fe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.");if(typeof t!="string")throw fe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(w.instance.useSha256ServiceRouting){fe("Using sha256 service routing");let a=w.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await Us(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw fe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(Hs,"externalServiceTunnelConfig");async function Ns(t,e){let n=Ds();if(n)if(fe(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(w.instance.useSha256ServiceRouting){fe("Using sha256 service routing");let d=w.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Us(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw fe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);fe(`Calling external service: ${c.toString()}`);let l=await pn(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw fe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw fe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(Ns,"externalServiceHandler");async function Us(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=cl(r);fe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ks(`${s}-${o}`),l=await ks(`${s}-${a}-${u}`);return`${c}.${l}`}i(Us,"hashServiceName");async function ks(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(ks,"hashSegment");function cl(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(cl,"sanitizeEnvironmentType");async function ll(t,e){let n=w.instance,r=e.route.handler.options,o=De(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await Hs(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let T in g.tunnelHeaders)p.set(T,g.tunnelHeaders[T])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(ll,"webSocketHandler");var Gr=i((t,e)=>t.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 y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Zs=i(async(t,e,n,r,o,s)=>{let a=t.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,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function qs(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Zs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(qs,"wireUpListeners");async function dl(t,e){let n=w.instance,r=e.route.handler.options,o=De(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new y("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let _=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${_}'`;throw new Error(h)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let b=r.policies&&r.policies.inbound?Gr(r.policies.inbound,"inbound"):[],T=r.policies&&r.policies.outbound?Gr(r.policies.outbound,"outbound"):[];return qs(m,I,t,e,b),qs(I,m,t,e,T),new Response(null,{status:101,webSocket:p})}i(dl,"webSocketPipelineHandler");var Wr=class extends Y{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new $("dyna-trace-log-transport",10,this.#i)};var Kr=class extends Y{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Qr(this.options)}},Yr=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function pl(t,e){return btoa(`${t}:${e}`)}i(pl,"createBasicDigest");var Qr=class{static{i(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=pl(e.username,e.password),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Yr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let s={stream:r,message:Oe(oe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new $("loki-log-transport",10,this.#s)};var Xr=class extends Y{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
68
+ `),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),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new $("sumo-logic-log-transport",10,this.#s)};var ml="d3a5b78f823648f5b1df4fe269d41172",to=class extends Y{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new no(this.options)}},no=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??ml}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.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,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=ds(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),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=Cr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let n=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new $("vmware-log-insights-log-transport",10,this.#a)};var ro=class extends Y{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new oo(this.options)}},oo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new $("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new Xe({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Oe(oe(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var io=new WeakMap,gl={tags:[]},so=class extends Ne{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ao(this.options)}static setContext(n,r){let o=io.get(n);o||(o=gl);let s=Object.assign({...o},r);io.set(n,s)}},ao=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,n){this.#i===void 0&&(this.#i=new $("data-dog-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(io.get(n)?.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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new uo(await r.text())}},uo=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var co=new WeakMap,fl={dimensions:[]},lo=class extends Ne{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new po(this.options)}static setContext(n,r){let o=co.get(n);o||(o=fl);let s=Object.assign({...o},r);co.set(n,s)}},po=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,n){this.#r===void 0&&(this.#r=new $("dynatrace-metrics-transport",10,this.dispatchFunction,B.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(co.get(n)?.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}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
69
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new mo(await r.text())}},mo=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var go=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var fo=class extends Te{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new ho(e,this.#e,this.#t)}},$s=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),hl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ho=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...hl};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 $("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?$s(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?$s(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)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(m=>{n.log.error(m)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var yo=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}},Ie=class extends yo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var yl="v1",bl=300;async function Fs(t,e,n,r=bl,o){return await Rl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(Fs,"constructEventAsync");function wl(t,e){return`${e.timestamp}.${t}`}i(wl,"makeHMACContent");async function Rl(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Pl(t,e,yl),l=/\s/.test(n),d=await xl(wl(a,u),n);return El(a,s,u,d,r,c,l,o)}i(Rl,"verifyHeaderAsync");function Pl(t,e,n){if(!t)throw new Ie(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;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 Ie(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Il(a,n);if(!u||u.timestamp===-1)throw new Ie(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ie(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Pl,"parseEventDetails");function El(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(m=>Tl(m,r)).length,l=`
70
70
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
71
71
 
72
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Ee(e,t,{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.
72
+ Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Ie(e,t,{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.
73
73
  Signature verification is impossible without access to the original signed material.
74
74
  `+l+`
75
- `+d}):new Ee(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
75
+ `+d}):new Ie(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
76
76
  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.
77
77
  `+l+`
78
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Ee(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Rl,"validateComputedSignature");function Pl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Pl,"parseHeader");function El(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(El,"secureCompare");async function Il(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),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(Il,"computeHMACSignatureAsync");var ho=new Array(256);for(let t=0;t<ho.length;t++)ho[t]=t.toString(16).padStart(2,"0");function G(t,e,n="policy"){let r=`${n} '${e}'`;if(!qe(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' 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 d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(G,"optionValidator");var St=class extends we{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){G(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 qs(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 n.log.error("Error validating stripe webhook",s),T.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function $s(t){return t!==null&&typeof t=="object"&&"id"in t&&ae(t.id)&&"type"in t&&ae(t.type)}i($s,"isStripeWebhookEvent");var xl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new A(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new A(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new A(s)}return o}},pn=xl;var yo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Fs="My API Key";async function Bs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,yo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Fs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(Bs,"createConsumer");async function zs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,yo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Fs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(zs,"createConsumerInvite");async function js({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,yo);o.searchParams.set("with-api-key","true");let s=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(n)},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 n.log.error(u,a),new A(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(js,"deleteConsumer");async function Vs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!We(d))throw new q("No Zuplo JWT token set.");let m=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new A(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(Vs,"createSubscription");async function Ot({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!We(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.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 t.log.error(u,c),new A(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Ot,"updateSubscription");async function Ct({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!We(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.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 t.log.error(c,l),new A(`${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 t.log.error(c),new A(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}return u.data[0]}i(Ct,"getSubscription");var V="Unable to process webhook event.",ze="Successfully processed webhook event",le="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function mn(t){return t.replaceAll("_","-")}i(mn,"stripeStatusToMeteringStatus");async function bo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await Bs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await pn.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.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await zs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return T.internalServerError(t,e,{title:V,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=mn(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await Vs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await js({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{title:V,detail:p.message})}return T.ok(t,e,{title:ze})}i(bo,"onCustomerSubscriptionCreated");async function wo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});try{let a=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Ot({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.internalServerError(t,e,{title:V,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. `+le})}return T.ok(t,e,{title:ze})}i(wo,"onCustomerSubscriptionDeleted");async function Ro(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.badRequest(t,e,{title:V,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=mn(n.data.object.status);await Ot({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return T.internalServerError(t,e,{title:V,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. `+le})}return T.ok(t,e,{title:ze})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await pn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Ot({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.internalServerError(t,e,{title:V,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. `+le})}return T.ok(t,e,{title:ze})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),T.badRequest(t,e,{title:V,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."+le})}i(Ro,"onCustomerSubscriptionUpdated");var Gs=class extends $t{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,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(se.ZUPLO_METERING_SERVICE_BUCKET_ID)d=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!vl(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!$s(g))return T.badRequest(c,l,{title:V,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+le});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await bo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Ro(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await wo(c,l,g,{meteringBucketId:d});default:return T.badRequest(c,l,{title:V,detail:`Event '${g.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.`+le})}},"stripeWebhookHandler"),s=Qi({inboundPolicies:[new St({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});G(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function vl(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(vl,"isMetricsRegion");var Ks=new WeakMap,Ws={},Po=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ks.set(e,n)}};async function Tl(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ke(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ks.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new A(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=$e(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},m=Ws[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new $("amberflo-ingest-meter",10,async b=>{try{let x=n.url??"https://app.amberflo.io/ingest",L=await fetch(x,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});L.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${L.status}: ${await L.text()}`)}catch(x){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${x.message}`),x}}),Ws[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(Tl,"AmberfloMeteringInboundPolicy");async function gn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(gn,"sha256");var Js=new Map;async function ee(t,e){let n,r=Js.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await gn(JSON.stringify({policyName:t,options:e}))}`,Js.set(t,n)),n}i(ee,"getPolicyCacheName");var Ys="key-metadata-cache-type";function Sl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Sl,"getKeyValue");async function Eo(t,e,n,r){if(!n.bucketName)if(se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(x=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:x}),"unauthorizedResponse"),a=t.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=Sl(a,o);if(!u||u==="")return s("No key present");let c=await Ol(u),l=await ee(r,o),d=new Q(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ys&&B.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let x=await g.text(),L=JSON.parse(x);e.log.error("Unexpected response from key service",L)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:Ys,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(Eo,"ApiKeyInboundPolicy");async function Ol(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ol,"hashValue");var Cl=Eo;import{createRemoteJWKSet as Al,jwtVerify as Qs}from"jose";var Io={},Ll=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");Io[e.jwkUrl]||(Io[e.jwkUrl]=Al(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await Qs(t,Io[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),_l=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await Qs(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),re=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>T.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Ll:_l,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Nl=i(async(t,e,n,r)=>re(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var kl=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Ml=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Dl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Dl,"digestMessage");var Hl=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Dl(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ul(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Hl(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);Ml.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Ul,"CachingInboundPolicy");var Zl=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(t,{method:n.method})},"ChangeMethodInboundPolicy");var ql=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new z(t,{headers:o})},"ClearHeadersInboundPolicy");var $l=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Fl=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",re(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Bl=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return re(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var zl=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=X.instance,s=ht(n.policies,o?.routeData.policies);return xr(s)(t,e)},"CompositeInboundPolicy");var jl=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let s=Vl(o);if(!s)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Q(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Vl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(Vl,"getToken");var Gl=i(async(t,e,n,r)=>(G(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),re(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Wl=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.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(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new z(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var et="__unknown__",Kl=i(async(t,e,n,r)=>{let o={allow:{countries:nt(n.allow?.countries,"allow.countries",r),regionCodes:nt(n.allow?.regionCodes,"allow.regionCode",r),asns:nt(n.allow?.asns,"allow.asOrganization",r)},block:{countries:nt(n.block?.countries,"block.countries",r),regionCodes:nt(n.block?.regionCodes,"block.regionCode",r),asns:nt(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??et,a=e.incomingRequestProperties.regionCode?.toLowerCase()??et,u=e.incomingRequestProperties.asn?.toString()??et,c=o.ignoreUnknown&&s===et,l=o.ignoreUnknown&&a===et,d=o.ignoreUnknown&&u===et,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return tt(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,x=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||x.length>0&&x.includes(u)&&!d?tt(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function tt(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(tt,"blockedResponse");function nt(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(nt,"toLowerStringArray");var Jl=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Yl=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return xo(r,t,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 xo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Xs(a[u])}else return a.length>0?Xs(a[0]):xo(r,t,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 Xs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(Xs,"generateResponse");var xo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ql="Incoming",Xl={logRequestBody:!0,logResponseBody:!0};function ea(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(ea,"headersToObject");function ta(){return new Date().toISOString()}i(ta,"timestamp");var vo=new WeakMap,ed={};function td(t,e){let n=vo.get(t);n||(n=ed);let r=Object.assign({...n},e);vo.set(t,r)}i(td,"setMoesifContext");async function na(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(na,"readBody");var nd={},To;function ra(){if(!To)throw new A("Invalid State - no _lastLogger");return To}i(ra,"getLastLogger");function rd(t){let e=nd[t];return e||(e=new $("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ra().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ra().error({status:o.status,body:await o.text()})})),e}i(rd,"getDispatcher");async function od(t,e,n,r){To=e.log;let o=ta(),s=Object.assign(Xl,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await na(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=rd(s.applicationId),d=t.headers.get("true-client-ip"),p=vo.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ea(t.headers)},g=s.logResponseBody?await na(u,e):void 0,I={time:ta(),status:u.status,headers:ea(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ql};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(od,"MoesifInboundPolicy");async function oa(t,e,n,r){let o=B.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(oa,"loadSubscription");async function ia(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=B.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(ia,"consumeSubcriptionQuotas");var id=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function fn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(fn,"validateMeters");function sa(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Fe(t),r=[];for(let o of n)id.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(sa,"parseAllowedSubscriptionStatuses");function aa(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(aa,"compareMeters");var So=class extends we{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return me.get(e,st)}static setMeters(e,n){fn(n,"setMeters"),me.set(e,kt,n)}async handler(e,n){G(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=Ke(this.options.meterOnStatusCodes),s=me.get(n,kt),a={...this.options.meters,...s};fn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=sa(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,x,L)=>{let f=me.get(L,st);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=me.get(L,kt),H={...this.options.meters,...O};if(fn(H,this.policyName),o.includes(b.status)&&f&&H){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:R}=aa(f.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await ia(L,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await oa(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),me.set(n,st,p));let m=me.get(n,st);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),T.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var sd=i(async(t,e,n,r)=>re(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as ad}from"jose";var Oo,ud=i(async(t,e,n,r)=>{if(!Oo)try{Oo=await ad(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return re(t,e,{issuer:n.authUrl,secret:Oo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var pa=Se(Ae());var ca=Se(Ae());var hn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Co=class extends hn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ao=class extends hn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function cd(t,e){if(zi(t))throw new Co(e)}i(cd,"throwIfUndefinedOrNull");function At(t,e){if(cd(t,e),!ae(t))throw new Ao(e,"string")}i(At,"throwIfNotString");var yn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return At(e,"redisClientUrl"),At(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){At(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},bn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(At(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new q("The in-memory redis client only supports /rate-limit calls")}};var ld=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Rn=i(async t=>({key:`ip-${ld(t)}`}),"getIP"),Pn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),En=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),wn;function In(t,e){let n;if(wn)return wn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new bn,wn=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ae(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ae(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=yn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return wn=n,n}i(In,"getRedisClient");async function xn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(xn,"getCountAndUpdateExpiry");function vn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(vn,"wrapUserFunction");var Tn="Retry-After";var ua=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),la=i(async(t,e,n,r)=>{let o=B.getLogger(e),s=i((h,R)=>{let S={};return(!h||h==="retry-after")&&(S[Tn]=R.toString()),T.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:vn(n,r),user:Pn,ip:Rn,all:En}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=In(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,x=await ee(r,n),L=new Q(x,e),f=xn(b,p,g,o,e.requestId),P;i(async()=>{let h=await f;if(h.count>d){let R=Date.now()+h.ttlSeconds*1e3;L.put(b,R,h.ttlSeconds),ua(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,h.ttlSeconds)}},"asyncCheck")();let H=await L.get(b);if(H!==void 0&&H>Date.now()){ua(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((H-Date.now())/1e3);return s(m,h)}return e.addResponseSendingHook(async h=>P??h),t},"AsyncRateLimitInboundPolicy");var da=(0,pa.debug)("zuplo:policies:RateLimitInboundPolicy"),dd="strict",ma=i(async(t,e,n,r)=>{if((n.mode??dd)==="async")return la(t,e,n,r);let s=Date.now(),a=B.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Tn]=d.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:vn(n,r),user:Pn,ip:Rn,all:En}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",x=In(r,a),f=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await xn(f,I,x,a,e.requestId);return P.count>g?(da(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;da(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Lo;function ga(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(ga,"headersToNameValuePairs");function pd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(pd,"queryToNameValueParis");function md(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(md,"parseIntOrUndefined");var fa={};async function gd(t,e,n,r){let o=new Date,s=Date.now();return Lo||(Lo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?$e(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?$e(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Lo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ga(t.headers),queryString:pd(t.query)},response:{status:a.status,statusText:a.statusText,headers:ga(a.headers),content:{size:md(t.headers.get("content-length"))}}}]}}},d=fa[n.apiKey];if(!d){let p=n.apiKey;d=new $("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),fa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(gd,"ReadmeMetricsInboundPolicy");var fd=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new z(t,{headers:s})},"RemoveHeadersInboundPolicy");var hd=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var yd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new z(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var bd=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ha=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),wd=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?ha():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ha():t},"RequestSizeLimitInboundPolicy");function Rd(t,e,n){return`_${je(t+"_"+e+"_"+n)}`}i(Rd,"getRawOperationDataIdentifierName");function _o(t,e,n,r){return`_${je(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(_o,"getIdForParameterSchema");function No(t,e,n){return`_${je(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${je(n.toLowerCase())}`}i(No,"getIdForRequestBodySchema");function Pd(t,e){return`_${je(t)}__${je(e)}`}i(Pd,"getIdForRefSchema");function je(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(je,"sanitizedIdentifierName");var rt=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),ot=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.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=_o(n,r,o,c.name),p=X.instance.schemaValidator[d],m=p(e[c.name]),g=ko(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),fe=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),he=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ye=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),ko=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ya(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(he(n.validateBody)&&fe(t,n.logLevel??"info",I,[r],g),ye(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=T.badRequest(e,t,{detail:g});return he(n.validateBody)&&fe(t,n.logLevel??"info",g,[r],[g]),ye(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=No(t.route.path,e.method,o),u=X.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=T.badRequest(e,t,{detail:g});return he(n.validateBody)&&fe(t,n.logLevel??"info",g,[r],[g]),ye(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=ko(l),m=T.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(he(n.validateBody)&&fe(t,n.logLevel??"info",d,[r],p),ye(n.validateBody))return m}i(ya,"handleBodyValidation");function ba(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=rt(t),s=ot(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(he(n.validateHeaders)&&fe(t,n.logLevel??"info",a,s.invalidValues,s.errors),ye(n.validateHeaders))return u}}i(ba,"handleHeadersValidation");function wa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=rt(t),o=ot(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(he(n.validatePathParameters)&&fe(t,n.logLevel??"info",s,o.invalidValues,o.errors),ye(n.validatePathParameters))return a}}i(wa,"handlePathParameterValidation");function Ra(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=rt(t),o=ot(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(he(n.validateQueryParameters)&&fe(t,n.logLevel??"info",s,o.invalidValues,o.errors),ye(n.validateQueryParameters))return a}}i(Ra,"handleQueryParameterValidation");var Pa=i(async(t,e,n)=>{let r=Ra(e,t,n);if(r!==void 0||(r=wa(e,t,n),r!==void 0)||(r=ba(e,t,n),r!==void 0))return r;let o=await ya(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ed=Pa;var Id=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var xd=i(async(t,e,n)=>new z(t,{body:n.body}),"SetBodyInboundPolicy");var vd=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`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 z(t,{headers:s})},"SetHeadersInboundPolicy");var Td=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`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(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Sd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`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 z(s.toString(),t)},"SetQueryParamsInboundPolicy");var Od=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Cd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ad=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Cd(n.sleepInMs),t},"SleepInboundPolicy");var Ld=i(async(t,e,n,r)=>{G(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await re(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof z))throw new q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new A(`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?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var _d=i(async(t,e,n,r)=>{G(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Q(o,e),a=await s.get(r);if(!a){let u=await Nd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Nd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("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 A("Response returned from Azure AD is not in the expected format.")}i(Nd,"getAccessToken");var Ea="https://accounts.google.com/o/oauth2/token",Mo,kd=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string"),Mo||(Mo=await ue.init(n.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 ee(r,n),a=new Q(s,e),u=await a.get(r);if(!u){let c=await Re({serviceAccount:Mo,audience:Ea,payload:o}),l=await Xt(Ea,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Md="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Dd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Do,Hd=i(async(t,e,n,r)=>{if(G(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Dd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Do||(Do=await ue.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new A(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=$e(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Q(a,e),c={uid:s,claims:o},l=await gn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Re({serviceAccount:Do,audience:Md,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await us(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Ho,Ud=i(async(t,e,n,r)=>{G(n,r).required("audience","string").required("serviceAccountJson","string"),Ho||(Ho=await ue.init(n.serviceAccountJson));let o=await Re({serviceAccount:Ho,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ia="https://www.googleapis.com/oauth2/v4/token",Uo,Zd=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Uo||(Uo=await ue.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=Fe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await ee(r,n),a;n.useMemoryCacheOnly?a=new Ge(s):a=new Q(s,e);let u=await a.get(r);if(!u){let c=await Re({serviceAccount:Uo,audience:Ia,payload:o}),l=await Xt(Ia,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var qd=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new q("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 T.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Sa=Se(Ta());var qo=class extends Ne{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),G(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?Ke(e.parseOnStatusCodes):void 0,this.parser=new Sa.XMLParser({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,n,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 A(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 $o=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Fo=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new $(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),un().waitUntil(this.#e.waitUntilFlushed())}};var Bo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new Lt(r)),await new Lt(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new Lt(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},Lt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){un().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var zo=["sha-1","sha-256","sha-384","sha-512"],Sn=class{static{i(this,"BaseCryptoBeta")}};var jo=class extends Sn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!zo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${zo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var On=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Vo=class extends On{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new _t("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{cc as API_KEY,to as AWSLoggingPlugin,Tl as AmberfloMeteringInboundPolicy,Po as AmberfloMeteringPolicy,Cl as ApiAuthKeyInboundPolicy,Eo as ApiKeyInboundPolicy,po as AuditLogDataStaxProvider,mo as AuditLogPlugin,Nl as Auth0JwtInboundPolicy,Vc as AwsLambdaHandlerExtensions,Fo as BackgroundDispatcher,Bo as BackgroundLoader,kl as BasicAuthInboundPolicy,ma as BasicRateLimitInboundPolicy,$ as BatchDispatch,Ul as CachingInboundPolicy,Zl as ChangeMethodInboundPolicy,ql as ClearHeadersInboundPolicy,$l as ClearHeadersOutboundPolicy,Fl as ClerkJwtInboundPolicy,Bl as CognitoJwtInboundPolicy,zl as CompositeInboundPolicy,y as ConfigurationError,ar as ContentTypes,me as ContextData,jo as CryptoBeta,jl as CurityPhantomTokenInboundPolicy,Nr as DataDogLoggingPlugin,oo as DataDogMetricsPlugin,Vr as DynaTraceLoggingPlugin,uo as DynatraceMetricsPlugin,Gl as FirebaseJwtInboundPolicy,Wl as FormDataToJsonInboundPolicy,Kl as GeoFilterInboundPolicy,Or as GoogleCloudLoggingPlugin,Ur as Handler,T as HttpProblems,lr as HttpStatusCode,we as InboundPolicy,Jl as JWTScopeValidationInboundPolicy,Vo as KeyValueStore,Wr as LokiLoggingPlugin,It as LookupResult,Q as MemoryZoneReadThroughCache,Yl as MockApiInboundPolicy,od as MoesifInboundPolicy,So as MonetizationInboundPolicy,sd as OktaJwtInboundPolicy,re as OpenIdJwtInboundPolicy,Ne as OutboundPolicy,Ze as ProblemResponseFormatter,ud as PropelAuthJwtInboundPolicy,ma as RateLimitInboundPolicy,gd as ReadmeMetricsInboundPolicy,fd as RemoveHeadersInboundPolicy,hd as RemoveHeadersOutboundPolicy,yd as RemoveQueryParamsInboundPolicy,bd as ReplaceStringOutboundPolicy,wd as RequestSizeLimitInboundPolicy,Pa as RequestValidationInboundPolicy,Id as RequireOriginInboundPolicy,pt as ResponseSendingEvent,mt as ResponseSentEvent,xt as Router,A as RuntimeError,Jt as SYSTEM_LOGGER,Ed as SchemaBasedRequestValidation,$o as ServiceProviderImpl,xd as SetBodyInboundPolicy,vd as SetHeadersInboundPolicy,Td as SetHeadersOutboundPolicy,Sd as SetQueryParamsInboundPolicy,Od as SetStatusOutboundPolicy,Ad as SleepInboundPolicy,Gs as StripeMonetizationPlugin,St as StripeWebhookVerificationInboundPolicy,Yr as SumoLogicLoggingPlugin,Ld as SupabaseJwtInboundPolicy,B as SystemLogMap,ve as SystemRouteName,ut as TelemetryPlugin,_d as UpstreamAzureAdServiceAuthInboundPolicy,kd as UpstreamFirebaseAdminAuthInboundPolicy,Hd as UpstreamFirebaseUserAuthInboundPolicy,Ud as UpstreamGcpJwtInboundPolicy,Zd as UpstreamGcpServiceAuthInboundPolicy,Xr as VMWareLogInsightLoggingPlugin,qd as ValidateJsonSchemaInbound,qo as XmlToJsonOutboundPolicy,it as ZoneCache,z as ZuploRequest,Gc as awsLambdaHandler,se as environment,_o as getIdForParameterSchema,Pd as getIdForRefSchema,No as getIdForRequestBodySchema,Rd as getRawOperationDataIdentifierName,dr as httpStatuses,ys as isRestrictedEnvVariableName,bs as isZuploReadableEnvVariableName,tl as openApiSpecHandler,vt as originalFetch,Lc as purgeGatewayCache,rl as redirectHandler,je as sanitizedIdentifierName,ur as serialize,td as setMoesifContext,il as urlForwardHandler,al as urlRewriteHandler,ul as webSocketHandler,cl as webSocketPipelineHandler};
78
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Ie(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(El,"validateComputedSignature");function Il(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Il,"parseHeader");function Tl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Tl,"secureCompare");async function xl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=bo[s[u]];return a.join("")}i(xl,"computeHMACSignatureAsync");var bo=new Array(256);for(let t=0;t<bo.length;t++)bo[t]=t.toString(16).padStart(2,"0");function G(t,e,n="policy"){let r=`${n} '${e}'`;if(!$e(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' 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 d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(G,"optionValidator");var Ot=class extends Re{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){G(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 Fs(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 n.log.error("Error validating stripe webhook",s),O.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Bs(t){return t!==null&&typeof t=="object"&&"id"in t&&ae(t.id)&&"type"in t&&ae(t.type)}i(Bs,"isStripeWebhookEvent");var vl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new A(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new A(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new A(s)}return o}},mn=vl;var wo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",zs="My API Key";async function js({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,wo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:zs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(js,"createConsumer");async function Vs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,wo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:zs,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Vs,"createConsumerInvite");async function Gs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,wo);o.searchParams.set("with-api-key","true");let s=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(n)},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 n.log.error(u,a),new A(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Gs,"deleteConsumer");async function Ws({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!Ke(d))throw new q("No Zuplo JWT token set.");let m=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new A(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(Ws,"createSubscription");async function St({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ke(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.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 t.log.error(u,c),new A(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(St,"updateSubscription");async function Ct({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ke(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.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 t.log.error(c,l),new A(`${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 t.log.error(c),new A(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}return u.data[0]}i(Ct,"getSubscription");var V="Unable to process webhook event.",je="Successfully processed webhook event",le="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function gn(t){return t.replaceAll("_","-")}i(gn,"stripeStatusToMeteringStatus");async function Ro(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),O.badRequest(t,e,{title:V,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await js({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.`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Vs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return O.internalServerError(t,e,{title:V,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=gn(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await Ws({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await Gs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),O.internalServerError(t,e,{title:V,detail:p.message})}return O.ok(t,e,{title:je})}i(Ro,"onCustomerSubscriptionCreated");async function Po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),O.badRequest(t,e,{title:V,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});try{let a=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await St({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return O.internalServerError(t,e,{title:V,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. `+le})}return O.ok(t,e,{title:je})}i(Po,"onCustomerSubscriptionDeleted");async function Eo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{title:V,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),O.badRequest(t,e,{title:V,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+le});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=gn(n.data.object.status);await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return O.internalServerError(t,e,{title:V,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. `+le})}return O.ok(t,e,{title:je})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await mn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return O.internalServerError(t,e,{title:V,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. `+le})}return O.ok(t,e,{title:je})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),O.badRequest(t,e,{title:V,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."+le})}i(Eo,"onCustomerSubscriptionUpdated");var Js=class extends Ft{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,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(se.ZUPLO_METERING_SERVICE_BUCKET_ID)d=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Ol(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!Bs(g))return O.badRequest(c,l,{title:V,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+le});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Ro(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Eo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Po(c,l,g,{meteringBucketId:d});default:return O.badRequest(c,l,{title:V,detail:`Event '${g.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.`+le})}},"stripeWebhookHandler"),s=ns({inboundPolicies:[new Ot({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});G(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new K({processors:[ne,s],handler:o,gateway:r}),u=new J({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Ol(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(Ol,"isMetricsRegion");var Ys=new WeakMap,Ks={},Io=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ys.set(e,n)}};async function Sl(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ye(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ys.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new A(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Fe(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},m=Ks[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new $("amberflo-ingest-meter",10,async b=>{try{let T=n.url??"https://app.amberflo.io/ingest",_=await fetch(T,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),Ks[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(Sl,"AmberfloMeteringInboundPolicy");async function fn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(fn,"sha256");var Qs=new Map;async function X(t,e){let n,r=Qs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await fn(JSON.stringify({policyName:t,options:e}))}`,Qs.set(t,n)),n}i(X,"getPolicyCacheName");var Xs="key-metadata-cache-type";function Cl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Cl,"getKeyValue");async function To(t,e,n,r){if(!n.bucketName)if(se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?t:O.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),a=t.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=Cl(a,o);if(!u||u==="")return s("No key present");let c=await Al(u),l=await X(r,o),d=new Q(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Xs&&B.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await ie({retryDelayMs:5,retries:2,logger:B.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:Xs,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(To,"ApiKeyInboundPolicy");async function Al(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Al,"hashValue");var _l=To;import{createRemoteJWKSet as Ll,jwtVerify as ea}from"jose";var xo={},Nl=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");xo[e.jwkUrl]||(xo[e.jwkUrl]=Ll(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await ea(t,xo[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),kl=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await ea(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),re=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>O.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Nl:kl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ml=i(async(t,e,n,r)=>re(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Dl=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>O.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Hl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ul(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ul,"digestMessage");var Zl=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Ul(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ql(t,e,n,r){let o=await X(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Zl(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);Hl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(ql,"CachingInboundPolicy");var $l=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(t,{method:n.method})},"ChangeMethodInboundPolicy");var Fl=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new z(t,{headers:o})},"ClearHeadersInboundPolicy");var Bl=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var zl=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",re(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var jl=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return re(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Vl=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ee.instance,s=yt(n.policies,o?.routeData.policies);return vr(s)(t,e)},"CompositeInboundPolicy");var Gl=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return O.unauthorized(t,e,{detail:"No authorization header"});let s=Wl(o);if(!s)return O.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Q(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),O.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):O.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Wl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(Wl,"getToken");var Jl=i(async(t,e,n,r)=>(G(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),re(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Kl=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.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(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new z(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var nt="__unknown__",Yl=i(async(t,e,n,r)=>{let o={allow:{countries:ot(n.allow?.countries,"allow.countries",r),regionCodes:ot(n.allow?.regionCodes,"allow.regionCode",r),asns:ot(n.allow?.asns,"allow.asOrganization",r)},block:{countries:ot(n.block?.countries,"block.countries",r),regionCodes:ot(n.block?.regionCodes,"block.regionCode",r),asns:ot(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??nt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??nt,u=e.incomingRequestProperties.asn?.toString()??nt,c=o.ignoreUnknown&&s===nt,l=o.ignoreUnknown&&a===nt,d=o.ignoreUnknown&&u===nt,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return rt(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?rt(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function rt(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),O.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(rt,"blockedResponse");function ot(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(ot,"toLowerStringArray");var Ql=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Xl=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return vo(r,t,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 vo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ta(a[u])}else return a.length>0?ta(a[0]):vo(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ta(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(ta,"generateResponse");var vo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return O.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var ed="Incoming",td={logRequestBody:!0,logResponseBody:!0};function na(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(na,"headersToObject");function ra(){return new Date().toISOString()}i(ra,"timestamp");var Oo=new WeakMap,nd={};function rd(t,e){let n=Oo.get(t);n||(n=nd);let r=Object.assign({...n},e);Oo.set(t,r)}i(rd,"setMoesifContext");async function oa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(oa,"readBody");var od={},So;function ia(){if(!So)throw new A("Invalid State - no _lastLogger");return So}i(ia,"getLastLogger");function id(t){let e=od[t];return e||(e=new $("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ia().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ia().error({status:o.status,body:await o.text()})})),e}i(id,"getDispatcher");async function sd(t,e,n,r){So=e.log;let o=ra(),s=Object.assign(td,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await oa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=id(s.applicationId),d=t.headers.get("true-client-ip"),p=Oo.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:na(t.headers)},g=s.logResponseBody?await oa(u,e):void 0,I={time:ra(),status:u.status,headers:na(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ed};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(sd,"MoesifInboundPolicy");async function sa(t,e,n,r){let o=B.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(sa,"loadSubscription");async function aa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=B.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(aa,"consumeSubcriptionQuotas");var ad=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function hn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(hn,"validateMeters");function ua(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Be(t),r=[];for(let o of n)ad.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(ua,"parseAllowedSubscriptionStatuses");function ca(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(ca,"compareMeters");var Co=class extends Re{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,ut)}static setMeters(e,n){hn(n,"setMeters"),ge.set(e,Nt,n)}async handler(e,n){G(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=Ye(this.options.meterOnStatusCodes),s=ge.get(n,Nt),a={...this.options.meters,...s};hn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ua(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,T,_)=>{let h=ge.get(_,ut);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let v=ge.get(_,Nt),H={...this.options.meters,...v};if(hn(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=ca(h.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await aa(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:O.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await sa(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:O.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),O.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ge.set(n,ut,p));let m=ge.get(n,ut);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),O.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),O.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),O.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return O.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var ud=i(async(t,e,n,r)=>re(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as cd}from"jose";var Ao,ld=i(async(t,e,n,r)=>{if(!Ao)try{Ao=await cd(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return re(t,e,{issuer:n.authUrl,secret:Ao,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ga=Se(_e());var da=Se(_e());var yn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},_o=class extends yn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Lo=class extends yn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function dd(t,e){if(Wi(t))throw new _o(e)}i(dd,"throwIfUndefinedOrNull");function At(t,e){if(dd(t,e),!ae(t))throw new Lo(e,"string")}i(At,"throwIfNotString");var bn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return At(e,"redisClientUrl"),At(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){At(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},wn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(At(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new q("The in-memory redis client only supports /rate-limit calls")}};var pd=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Pn=i(async t=>({key:`ip-${pd(t)}`}),"getIP"),En=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),In=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Rn;function Tn(t,e){let n;if(Rn)return Rn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new wn,Rn=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ae(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ae(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=bn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Rn=n,n}i(Tn,"getRedisClient");async function xn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(xn,"getCountAndUpdateExpiry");function vn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(vn,"wrapUserFunction");var On="Retry-After";var la=(0,da.debug)("zuplo:policies:RateLimitInboundPolicy"),pa=i(async(t,e,n,r)=>{let o=B.getLogger(e),s=i((f,R)=>{let S={};return(!f||f==="retry-after")&&(S[On]=R.toString()),O.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:vn(n,r),user:En,ip:Pn,all:In}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=Tn(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,T=await X(r,n),_=new Q(T,e),h=xn(b,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),la(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){la(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),t},"AsyncRateLimitInboundPolicy");var ma=(0,ga.debug)("zuplo:policies:RateLimitInboundPolicy"),md="strict",fa=i(async(t,e,n,r)=>{if((n.mode??md)==="async")return pa(t,e,n,r);let s=Date.now(),a=B.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[On]=d.toString()),O.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:vn(n,r),user:En,ip:Pn,all:In}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",T=Tn(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await xn(h,I,T,a,e.requestId);return P.count>g?(ma(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;ma(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var No;function ha(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(ha,"headersToNameValuePairs");function gd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(gd,"queryToNameValueParis");function fd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(fd,"parseIntOrUndefined");var ya={};async function hd(t,e,n,r){let o=new Date,s=Date.now();return No||(No={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Fe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Fe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:No,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ha(t.headers),queryString:gd(t.query)},response:{status:a.status,statusText:a.statusText,headers:ha(a.headers),content:{size:fd(t.headers.get("content-length"))}}}]}}},d=ya[n.apiKey];if(!d){let p=n.apiKey;d=new $("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),ya[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(hd,"ReadmeMetricsInboundPolicy");var yd=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new z(t,{headers:s})},"RemoveHeadersInboundPolicy");var bd=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var wd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new z(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var Rd=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ba=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Pd=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?ba():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ba():t},"RequestSizeLimitInboundPolicy");function Ed(t,e,n){return`_${Ve(t+"_"+e+"_"+n)}`}i(Ed,"getRawOperationDataIdentifierName");function ko(t,e,n,r){return`_${Ve(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(ko,"getIdForParameterSchema");function Mo(t,e,n){return`_${Ve(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ve(n.toLowerCase())}`}i(Mo,"getIdForRequestBodySchema");function Id(t,e){return`_${Ve(t)}__${Ve(e)}`}i(Id,"getIdForRefSchema");function Ve(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(Ve,"sanitizedIdentifierName");var it=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),st=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.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=ko(n,r,o,c.name),p=ee.instance.schemaValidator[d],m=p(e[c.name]),g=Do(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),he=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),ye=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),be=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Do=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function wa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=O.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(ye(n.validateBody)&&he(t,n.logLevel??"info",I,[r],g),be(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=O.badRequest(e,t,{detail:g});return ye(n.validateBody)&&he(t,n.logLevel??"info",g,[r],[g]),be(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Mo(t.route.path,e.method,o),u=ee.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=O.badRequest(e,t,{detail:g});return ye(n.validateBody)&&he(t,n.logLevel??"info",g,[r],[g]),be(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Do(l),m=O.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(ye(n.validateBody)&&he(t,n.logLevel??"info",d,[r],p),be(n.validateBody))return m}i(wa,"handleBodyValidation");function Ra(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=it(t),s=st(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=O.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ye(n.validateHeaders)&&he(t,n.logLevel??"info",a,s.invalidValues,s.errors),be(n.validateHeaders))return u}}i(Ra,"handleHeadersValidation");function Pa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=it(t),o=st(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=O.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ye(n.validatePathParameters)&&he(t,n.logLevel??"info",s,o.invalidValues,o.errors),be(n.validatePathParameters))return a}}i(Pa,"handlePathParameterValidation");function Ea(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=it(t),o=st(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=O.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ye(n.validateQueryParameters)&&he(t,n.logLevel??"info",s,o.invalidValues,o.errors),be(n.validateQueryParameters))return a}}i(Ea,"handleQueryParameterValidation");var Ia=i(async(t,e,n)=>{let r=Ea(e,t,n);if(r!==void 0||(r=Pa(e,t,n),r!==void 0)||(r=Ra(e,t,n),r!==void 0))return r;let o=await wa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Td=Ia;var xd=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return O.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var vd=i(async(t,e,n)=>new z(t,{body:n.body}),"SetBodyInboundPolicy");var Od=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`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 z(t,{headers:s})},"SetHeadersInboundPolicy");var Sd=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`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(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Cd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`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 z(s.toString(),t)},"SetQueryParamsInboundPolicy");var Ad=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var _d=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ld=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await _d(n.sleepInMs),t},"SleepInboundPolicy");var Nd=i(async(t,e,n,r)=>{G(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await re(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof z))throw new q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new A(`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?O.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var kd=i(async(t,e,n,r)=>{G(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),s=new Q(o,e),a=await s.get(r);if(!a){let u=await Md(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Md(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("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 A("Response returned from Azure AD is not in the expected format.")}i(Md,"getAccessToken");var Ta="https://accounts.google.com/o/oauth2/token",Ho,Dd=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string"),Ho||(Ho=await ue.init(n.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 X(r,n),a=new Q(s,e),u=await a.get(r);if(!u){let c=await Pe({serviceAccount:Ho,audience:Ta,payload:o}),l=await Xt(Ta,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Hd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Ud=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Uo,Zd=i(async(t,e,n,r)=>{if(G(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Ud.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Uo||(Uo=await ue.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new A(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Fe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Q(a,e),c={uid:s,claims:o},l=await fn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Pe({serviceAccount:Uo,audience:Hd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await ps(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Zo,qd=i(async(t,e,n,r)=>{G(n,r).required("audience","string").required("serviceAccountJson","string"),Zo||(Zo=await ue.init(n.serviceAccountJson));let o=await Pe({serviceAccount:Zo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var xa="https://www.googleapis.com/oauth2/v4/token",qo,$d=i(async(t,e,n,r)=>{G(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),qo||(qo=await ue.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=Be(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await X(r,n),a;n.useMemoryCacheOnly?a=new We(s):a=new Q(s,e);let u=await a.get(r);if(!u){let c=await Pe({serviceAccount:qo,audience:xa,payload:o}),l=await Xt(xa,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Fd=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return O.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new q("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 O.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ca=Se(Sa());var Fo=class extends ke{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),G(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?Ye(e.parseOnStatusCodes):void 0,this.parser=new Ca.XMLParser({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,n,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 A(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 Bo=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var zo=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new $(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),un().waitUntil(this.#e.waitUntilFlushed())}};var jo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new _t(r)),await new _t(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new _t(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},_t=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){un().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var Vo=["sha-1","sha-256","sha-384","sha-512"],Sn=class{static{i(this,"BaseCryptoBeta")}};var Go=class extends Sn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!Vo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Vo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Cn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Wo=class extends Cn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new Mt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{ro as AWSLoggingPlugin,Sl as AmberfloMeteringInboundPolicy,Io as AmberfloMeteringPolicy,_l as ApiAuthKeyInboundPolicy,To as ApiKeyInboundPolicy,go as AuditLogDataStaxProvider,fo as AuditLogPlugin,Ml as Auth0JwtInboundPolicy,Vc as AwsLambdaHandlerExtensions,zo as BackgroundDispatcher,jo as BackgroundLoader,Dl as BasicAuthInboundPolicy,fa as BasicRateLimitInboundPolicy,$ as BatchDispatch,ql as CachingInboundPolicy,$l as ChangeMethodInboundPolicy,Fl as ClearHeadersInboundPolicy,Bl as ClearHeadersOutboundPolicy,zl as ClerkJwtInboundPolicy,jl as CognitoJwtInboundPolicy,Vl as CompositeInboundPolicy,y as ConfigurationError,cr as ContentTypes,ge as ContextData,Go as CryptoBeta,Gl as CurityPhantomTokenInboundPolicy,Mr as DataDogLoggingPlugin,so as DataDogMetricsPlugin,Wr as DynaTraceLoggingPlugin,lo as DynatraceMetricsPlugin,Jl as FirebaseJwtInboundPolicy,Kl as FormDataToJsonInboundPolicy,Yl as GeoFilterInboundPolicy,Ar as GoogleCloudLoggingPlugin,qr as Handler,O as HttpProblems,pr as HttpStatusCode,Re as InboundPolicy,Ql as JWTScopeValidationInboundPolicy,Wo as KeyValueStore,Kr as LokiLoggingPlugin,Tt as LookupResult,Q as MemoryZoneReadThroughCache,Xl as MockApiInboundPolicy,sd as MoesifInboundPolicy,Co as MonetizationInboundPolicy,ud as OktaJwtInboundPolicy,re as OpenIdJwtInboundPolicy,ke as OutboundPolicy,qe as ProblemResponseFormatter,ld as PropelAuthJwtInboundPolicy,fa as RateLimitInboundPolicy,hd as ReadmeMetricsInboundPolicy,yd as RemoveHeadersInboundPolicy,bd as RemoveHeadersOutboundPolicy,wd as RemoveQueryParamsInboundPolicy,Rd as ReplaceStringOutboundPolicy,Pd as RequestSizeLimitInboundPolicy,Ia as RequestValidationInboundPolicy,xd as RequireOriginInboundPolicy,mt as ResponseSendingEvent,gt as ResponseSentEvent,xt as Router,A as RuntimeError,kt as SYSTEM_LOGGER,Td as SchemaBasedRequestValidation,me as SemanticAttributes,Bo as ServiceProviderImpl,vd as SetBodyInboundPolicy,Od as SetHeadersInboundPolicy,Sd as SetHeadersOutboundPolicy,Cd as SetQueryParamsInboundPolicy,Ad as SetStatusOutboundPolicy,Ld as SleepInboundPolicy,Js as StripeMonetizationPlugin,Ot as StripeWebhookVerificationInboundPolicy,Xr as SumoLogicLoggingPlugin,Nd as SupabaseJwtInboundPolicy,ve as SystemRouteName,lt as TelemetryPlugin,kd as UpstreamAzureAdServiceAuthInboundPolicy,Dd as UpstreamFirebaseAdminAuthInboundPolicy,Zd as UpstreamFirebaseUserAuthInboundPolicy,qd as UpstreamGcpJwtInboundPolicy,$d as UpstreamGcpServiceAuthInboundPolicy,to as VMWareLogInsightLoggingPlugin,Fd as ValidateJsonSchemaInbound,Fo as XmlToJsonOutboundPolicy,at as ZoneCache,z as ZuploRequest,Gc as awsLambdaHandler,se as environment,ko as getIdForParameterSchema,Id as getIdForRefSchema,Mo as getIdForRequestBodySchema,Ed as getRawOperationDataIdentifierName,mr as httpStatuses,tl as openApiSpecHandler,rl as redirectHandler,Ve as sanitizedIdentifierName,lr as serialize,rd as setMoesifContext,il as urlForwardHandler,al as urlRewriteHandler,ll as webSocketHandler,dl as webSocketPipelineHandler};
79
79
  /*! For license information please see index.min.js.LEGAL.txt */