@zuplo/runtime 5.1563.0 → 5.1565.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.d.ts CHANGED
@@ -738,75 +738,6 @@ export declare interface HandlerDefinition {
738
738
  options?: unknown;
739
739
  }
740
740
 
741
- /**
742
- * @beta
743
- */
744
- declare interface HttpHeaders {
745
- accept?: string;
746
- "accept-language"?: string;
747
- "accept-patch"?: string;
748
- "accept-ranges"?: string;
749
- "access-control-allow-credentials"?: string;
750
- "access-control-allow-headers"?: string;
751
- "access-control-allow-methods"?: string;
752
- "access-control-allow-origin"?: string;
753
- "access-control-expose-headers"?: string;
754
- "access-control-max-age"?: string;
755
- "access-control-request-headers"?: string;
756
- "access-control-request-method"?: string;
757
- age?: string;
758
- allow?: string;
759
- "alt-svc"?: string;
760
- authorization?: string;
761
- "cache-control"?: string;
762
- connection?: string;
763
- "content-disposition"?: string;
764
- "content-encoding"?: string;
765
- "content-language"?: string;
766
- "content-length"?: string;
767
- "content-location"?: string;
768
- "content-range"?: string;
769
- "content-type"?: string;
770
- cookie?: string;
771
- date?: string;
772
- etag?: string;
773
- expect?: string;
774
- expires?: string;
775
- forwarded?: string;
776
- from?: string;
777
- host?: string;
778
- "if-match"?: string;
779
- "if-modified-since"?: string;
780
- "if-none-match"?: string;
781
- "if-unmodified-since"?: string;
782
- "last-modified"?: string;
783
- location?: string;
784
- origin?: string;
785
- pragma?: string;
786
- "proxy-authenticate"?: string;
787
- "proxy-authorization"?: string;
788
- "public-key-pins"?: string;
789
- range?: string;
790
- referer?: string;
791
- "retry-after"?: string;
792
- "sec-websocket-accept"?: string;
793
- "sec-websocket-extensions"?: string;
794
- "sec-websocket-key"?: string;
795
- "sec-websocket-protocol"?: string;
796
- "sec-websocket-version"?: string;
797
- "set-cookie"?: string[];
798
- "strict-transport-security"?: string;
799
- tk?: string;
800
- trailer?: string;
801
- "transfer-encoding"?: string;
802
- upgrade?: string;
803
- "user-agent"?: string;
804
- vary?: string;
805
- via?: string;
806
- warning?: string;
807
- "www-authenticate"?: string;
808
- }
809
-
810
741
  export declare type HttpMethod = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "CONNECT" | "OPTIONS" | "TRACE" | "PATCH";
811
742
 
812
743
  /**
@@ -2257,18 +2188,22 @@ export declare interface ParameterDefinition extends ParameterBaseObject {
2257
2188
  }
2258
2189
 
2259
2190
  /**
2260
- * @beta
2191
+ * This is the parsed values of the Cors configuration. All
2192
+ * values in the parsed configuration are in the format that the headers
2193
+ * use them (i.e. everything is converted to a string)
2261
2194
  */
2262
- declare interface PayloadResponseHeadersInit {
2263
- headers?: HttpHeaders;
2195
+ declare interface ParsedCorsPolicyConfiguration {
2196
+ name: string;
2197
+ allowCredentials: string | undefined;
2198
+ maxAge: string | undefined;
2199
+ allowedOrigins: string[];
2200
+ allowedMethods?: string;
2201
+ allowedHeaders?: string;
2202
+ exposeHeaders?: string;
2264
2203
  }
2265
2204
 
2266
- /**
2267
- * @beta
2268
- */
2269
- export declare interface PayloadResponseInit extends PayloadResponseHeadersInit {
2270
- status?: number;
2271
- statusText?: string;
2205
+ declare interface ParsedRouteData extends Omit<RouteData, "corsPolicies"> {
2206
+ corsPolicies: ParsedCorsPolicyConfiguration[];
2272
2207
  }
2273
2208
 
2274
2209
  export declare interface PolicyConfiguration {
package/index.minified.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var Fs=Object.create;var Me=Object.defineProperty;var $s=Object.getOwnPropertyDescriptor;var Bs=Object.getOwnPropertyNames;var zs=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var s=(t,e)=>Me(t,"name",{value:e,configurable:!0});var Ze=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vs=(t,e)=>{for(var n in e)Me(t,n,{get:e[n],enumerable:!0})},zr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Bs(e))!Gs.call(t,o)&&o!==n&&Me(t,o,{get:()=>e[o],enumerable:!(r=$s(e,o))||r.enumerable});return t};var Re=(t,e,n)=>(n=t!=null?Fs(zs(t)):{},zr(e||!t||!t.__esModule?Me(n,"default",{value:t,enumerable:!0}):n,t)),js=t=>zr(Me({},"__esModule",{value:!0}),t);var go=Ze(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.generateColor=h.colorFunctions=h.stripColor=h.bgRgb24=h.rgb24=h.bgRgb8=h.rgb8=h.bgBrightWhite=h.bgBrightCyan=h.bgBrightMagenta=h.bgBrightBlue=h.bgBrightYellow=h.bgBrightGreen=h.bgBrightRed=h.bgBrightBlack=h.bgWhite=h.bgCyan=h.bgMagenta=h.bgBlue=h.bgYellow=h.bgGreen=h.bgRed=h.bgBlack=h.brightWhite=h.brightCyan=h.brightMagenta=h.brightBlue=h.brightYellow=h.brightGreen=h.brightRed=h.brightBlack=h.gray=h.white=h.cyan=h.magenta=h.blue=h.yellow=h.green=h.red=h.black=h.strikethrough=h.hidden=h.inverse=h.underline=h.italic=h.dim=h.bold=h.reset=h.getColorEnabled=h.setColorEnabled=void 0;var oo=!0,_n=!oo;function Js(t){oo||(_n=t)}s(Js,"setColorEnabled");h.setColorEnabled=Js;function Ks(){return _n}s(Ks,"getColorEnabled");h.getColorEnabled=Ks;function x(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(x,"code");function O(t,e){return _n?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function Ws(t){return O(t,x([0],0))}s(Ws,"reset");h.reset=Ws;function Ys(t){return O(t,x([1],22))}s(Ys,"bold");h.bold=Ys;function Qs(t){return O(t,x([2],22))}s(Qs,"dim");h.dim=Qs;function Xs(t){return O(t,x([3],23))}s(Xs,"italic");h.italic=Xs;function ea(t){return O(t,x([4],24))}s(ea,"underline");h.underline=ea;function ta(t){return O(t,x([7],27))}s(ta,"inverse");h.inverse=ta;function na(t){return O(t,x([8],28))}s(na,"hidden");h.hidden=na;function ra(t){return O(t,x([9],29))}s(ra,"strikethrough");h.strikethrough=ra;function oa(t){return O(t,x([30],39))}s(oa,"black");h.black=oa;function io(t){return O(t,x([31],39))}s(io,"red");h.red=io;function so(t){return O(t,x([32],39))}s(so,"green");h.green=so;function ao(t){return O(t,x([33],39))}s(ao,"yellow");h.yellow=ao;function uo(t){return O(t,x([34],39))}s(uo,"blue");h.blue=uo;function co(t){return O(t,x([35],39))}s(co,"magenta");h.magenta=co;function lo(t){return O(t,x([36],39))}s(lo,"cyan");h.cyan=lo;function ia(t){return O(t,x([37],39))}s(ia,"white");h.white=ia;function sa(t){return po(t)}s(sa,"gray");h.gray=sa;function po(t){return O(t,x([90],39))}s(po,"brightBlack");h.brightBlack=po;function aa(t){return O(t,x([91],39))}s(aa,"brightRed");h.brightRed=aa;function ua(t){return O(t,x([92],39))}s(ua,"brightGreen");h.brightGreen=ua;function ca(t){return O(t,x([93],39))}s(ca,"brightYellow");h.brightYellow=ca;function la(t){return O(t,x([94],39))}s(la,"brightBlue");h.brightBlue=la;function da(t){return O(t,x([95],39))}s(da,"brightMagenta");h.brightMagenta=da;function pa(t){return O(t,x([96],39))}s(pa,"brightCyan");h.brightCyan=pa;function ga(t){return O(t,x([97],39))}s(ga,"brightWhite");h.brightWhite=ga;function ma(t){return O(t,x([40],49))}s(ma,"bgBlack");h.bgBlack=ma;function fa(t){return O(t,x([41],49))}s(fa,"bgRed");h.bgRed=fa;function ha(t){return O(t,x([42],49))}s(ha,"bgGreen");h.bgGreen=ha;function ya(t){return O(t,x([43],49))}s(ya,"bgYellow");h.bgYellow=ya;function ba(t){return O(t,x([44],49))}s(ba,"bgBlue");h.bgBlue=ba;function Ra(t){return O(t,x([45],49))}s(Ra,"bgMagenta");h.bgMagenta=Ra;function wa(t){return O(t,x([46],49))}s(wa,"bgCyan");h.bgCyan=wa;function Pa(t){return O(t,x([47],49))}s(Pa,"bgWhite");h.bgWhite=Pa;function Ea(t){return O(t,x([100],49))}s(Ea,"bgBrightBlack");h.bgBrightBlack=Ea;function Ia(t){return O(t,x([101],49))}s(Ia,"bgBrightRed");h.bgBrightRed=Ia;function xa(t){return O(t,x([102],49))}s(xa,"bgBrightGreen");h.bgBrightGreen=xa;function Oa(t){return O(t,x([103],49))}s(Oa,"bgBrightYellow");h.bgBrightYellow=Oa;function va(t){return O(t,x([104],49))}s(va,"bgBrightBlue");h.bgBrightBlue=va;function Ta(t){return O(t,x([105],49))}s(Ta,"bgBrightMagenta");h.bgBrightMagenta=Ta;function Ca(t){return O(t,x([106],49))}s(Ca,"bgBrightCyan");h.bgBrightCyan=Ca;function Aa(t){return O(t,x([107],49))}s(Aa,"bgBrightWhite");h.bgBrightWhite=Aa;function ie(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(ie,"clampAndTruncate");function La(t,e){return O(t,x([38,5,ie(e)],39))}s(La,"rgb8");h.rgb8=La;function Sa(t,e){return O(t,x([48,5,ie(e)],49))}s(Sa,"bgRgb8");h.bgRgb8=Sa;function _a(t,e){return typeof e=="number"?O(t,x([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,x([38,2,ie(e.r),ie(e.g),ie(e.b)],39))}s(_a,"rgb24");h.rgb24=_a;function Da(t,e){return typeof e=="number"?O(t,x([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,x([48,2,ie(e.r),ie(e.g),ie(e.b)],49))}s(Da,"bgRgb24");h.bgRgb24=Da;var ka=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 Ha(t){return t.replace(ka,"")}s(Ha,"stripColor");h.stripColor=Ha;h.colorFunctions=[io,so,ao,uo,co,lo];function Ua(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}s(Ua,"hashCode");function Na(t){let e=Math.abs(Ua(t));return h.colorFunctions[e%h.colorFunctions.length]}s(Na,"generateColor");h.generateColor=Na});var mo=Ze(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.format=void 0;function Ma(t,e,...n){let r=0,o=n.length,i=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(`
26
- `).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)?i+=" "+a:i+=" "+t(a);return i}s(Ma,"format");ct.format=Ma});var wo=Ze(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.inspect=void 0;function pe(t,e,n,r){let o={seen:[],stylize:Za,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Fa),lt(o,t,o.depth)}s(pe,"inspect");dt.inspect=pe;pe.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]};pe.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Za(t,e){return t}s(Za,"stylizeNoColor");function qa(t){return typeof t=="boolean"}s(qa,"isBoolean");function ho(t){return t===void 0}s(ho,"isUndefined");function Fa(t,e){let n=pe.styles[e];return n?"\x1B["+pe.colors[n][0]+"m"+t+"\x1B["+pe.colors[n][1]+"m":t}s(Fa,"stylizeWithColor");function Dn(t){return typeof t=="function"}s(Dn,"isFunction");function yo(t){return typeof t=="string"}s(yo,"isString");function $a(t){return typeof t=="number"}s($a,"isNumber");function bo(t){return t===null}s(bo,"isNull");function Ro(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Ro,"hasOwn");function kn(t){return Mn(t)&&Zn(t)==="[object RegExp]"}s(kn,"isRegExp");function Mn(t){return typeof t=="object"&&t!==null}s(Mn,"isObject");function Hn(t){return Mn(t)&&(Zn(t)==="[object Error]"||t instanceof Error)}s(Hn,"isError");function fo(t){return Mn(t)&&Zn(t)==="[object Date]"}s(fo,"isDate");function Zn(t){return Object.prototype.toString.call(t)}s(Zn,"objectToString");function Ba(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(Ba,"arrayToHash");function za(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)Ro(e,String(a))?i.push(Nn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Nn(t,e,n,r,a,!0))}),i}s(za,"formatArray");function Un(t){return"["+Error.prototype.toString.call(t)+"]"}s(Un,"formatError");function lt(t,e,n){if(t.customInspect&&e&&Dn(e.inspect)&&e.inspect!==pe&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return yo(d)||(d=lt(t,d,n)),d}let r=Ga(t,e);if(r)return r;let o=Object.keys(e),i=Ba(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Hn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Un(e);if(o.length===0){if(Dn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(kn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(fo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Hn(e))return Un(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Dn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),kn(e)&&(a=" "+RegExp.prototype.toString.call(e)),fo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Hn(e)&&(a=" "+Un(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return kn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=za(t,e,n,i,o):l=o.map(function(d){return Nn(t,e,n,i,d,u)}),t.seen.pop(),Va(l,a,c)}s(lt,"formatValue");function Nn(t,e,n,r,o,i){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")),Ro(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(bo(n)?u=lt(t,c.value,null):u=lt(t,c.value,n-1),u.indexOf(`
25
+ "use strict";var Gs=Object.create;var Ze=Object.defineProperty;var js=Object.getOwnPropertyDescriptor;var Js=Object.getOwnPropertyNames;var Ks=Object.getPrototypeOf,Ws=Object.prototype.hasOwnProperty;var s=(t,e)=>Ze(t,"name",{value:e,configurable:!0});var qe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ys=(t,e)=>{for(var n in e)Ze(t,n,{get:e[n],enumerable:!0})},jr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Js(e))!Ws.call(t,o)&&o!==n&&Ze(t,o,{get:()=>e[o],enumerable:!(r=js(e,o))||r.enumerable});return t};var we=(t,e,n)=>(n=t!=null?Gs(Ks(t)):{},jr(e||!t||!t.__esModule?Ze(n,"default",{value:t,enumerable:!0}):n,t)),Qs=t=>jr(Ze({},"__esModule",{value:!0}),t);var ho=qe(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.generateColor=h.colorFunctions=h.stripColor=h.bgRgb24=h.rgb24=h.bgRgb8=h.rgb8=h.bgBrightWhite=h.bgBrightCyan=h.bgBrightMagenta=h.bgBrightBlue=h.bgBrightYellow=h.bgBrightGreen=h.bgBrightRed=h.bgBrightBlack=h.bgWhite=h.bgCyan=h.bgMagenta=h.bgBlue=h.bgYellow=h.bgGreen=h.bgRed=h.bgBlack=h.brightWhite=h.brightCyan=h.brightMagenta=h.brightBlue=h.brightYellow=h.brightGreen=h.brightRed=h.brightBlack=h.gray=h.white=h.cyan=h.magenta=h.blue=h.yellow=h.green=h.red=h.black=h.strikethrough=h.hidden=h.inverse=h.underline=h.italic=h.dim=h.bold=h.reset=h.getColorEnabled=h.setColorEnabled=void 0;var ao=!0,_n=!ao;function Xs(t){ao||(_n=t)}s(Xs,"setColorEnabled");h.setColorEnabled=Xs;function ea(){return _n}s(ea,"getColorEnabled");h.getColorEnabled=ea;function x(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(x,"code");function O(t,e){return _n?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function ta(t){return O(t,x([0],0))}s(ta,"reset");h.reset=ta;function na(t){return O(t,x([1],22))}s(na,"bold");h.bold=na;function ra(t){return O(t,x([2],22))}s(ra,"dim");h.dim=ra;function oa(t){return O(t,x([3],23))}s(oa,"italic");h.italic=oa;function ia(t){return O(t,x([4],24))}s(ia,"underline");h.underline=ia;function sa(t){return O(t,x([7],27))}s(sa,"inverse");h.inverse=sa;function aa(t){return O(t,x([8],28))}s(aa,"hidden");h.hidden=aa;function ua(t){return O(t,x([9],29))}s(ua,"strikethrough");h.strikethrough=ua;function ca(t){return O(t,x([30],39))}s(ca,"black");h.black=ca;function uo(t){return O(t,x([31],39))}s(uo,"red");h.red=uo;function co(t){return O(t,x([32],39))}s(co,"green");h.green=co;function lo(t){return O(t,x([33],39))}s(lo,"yellow");h.yellow=lo;function po(t){return O(t,x([34],39))}s(po,"blue");h.blue=po;function go(t){return O(t,x([35],39))}s(go,"magenta");h.magenta=go;function mo(t){return O(t,x([36],39))}s(mo,"cyan");h.cyan=mo;function la(t){return O(t,x([37],39))}s(la,"white");h.white=la;function da(t){return fo(t)}s(da,"gray");h.gray=da;function fo(t){return O(t,x([90],39))}s(fo,"brightBlack");h.brightBlack=fo;function pa(t){return O(t,x([91],39))}s(pa,"brightRed");h.brightRed=pa;function ga(t){return O(t,x([92],39))}s(ga,"brightGreen");h.brightGreen=ga;function ma(t){return O(t,x([93],39))}s(ma,"brightYellow");h.brightYellow=ma;function fa(t){return O(t,x([94],39))}s(fa,"brightBlue");h.brightBlue=fa;function ha(t){return O(t,x([95],39))}s(ha,"brightMagenta");h.brightMagenta=ha;function ya(t){return O(t,x([96],39))}s(ya,"brightCyan");h.brightCyan=ya;function ba(t){return O(t,x([97],39))}s(ba,"brightWhite");h.brightWhite=ba;function Ra(t){return O(t,x([40],49))}s(Ra,"bgBlack");h.bgBlack=Ra;function wa(t){return O(t,x([41],49))}s(wa,"bgRed");h.bgRed=wa;function Pa(t){return O(t,x([42],49))}s(Pa,"bgGreen");h.bgGreen=Pa;function Ea(t){return O(t,x([43],49))}s(Ea,"bgYellow");h.bgYellow=Ea;function Ia(t){return O(t,x([44],49))}s(Ia,"bgBlue");h.bgBlue=Ia;function xa(t){return O(t,x([45],49))}s(xa,"bgMagenta");h.bgMagenta=xa;function Oa(t){return O(t,x([46],49))}s(Oa,"bgCyan");h.bgCyan=Oa;function va(t){return O(t,x([47],49))}s(va,"bgWhite");h.bgWhite=va;function Ta(t){return O(t,x([100],49))}s(Ta,"bgBrightBlack");h.bgBrightBlack=Ta;function Ca(t){return O(t,x([101],49))}s(Ca,"bgBrightRed");h.bgBrightRed=Ca;function Aa(t){return O(t,x([102],49))}s(Aa,"bgBrightGreen");h.bgBrightGreen=Aa;function La(t){return O(t,x([103],49))}s(La,"bgBrightYellow");h.bgBrightYellow=La;function Sa(t){return O(t,x([104],49))}s(Sa,"bgBrightBlue");h.bgBrightBlue=Sa;function _a(t){return O(t,x([105],49))}s(_a,"bgBrightMagenta");h.bgBrightMagenta=_a;function Da(t){return O(t,x([106],49))}s(Da,"bgBrightCyan");h.bgBrightCyan=Da;function ka(t){return O(t,x([107],49))}s(ka,"bgBrightWhite");h.bgBrightWhite=ka;function ie(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(ie,"clampAndTruncate");function Ha(t,e){return O(t,x([38,5,ie(e)],39))}s(Ha,"rgb8");h.rgb8=Ha;function Ua(t,e){return O(t,x([48,5,ie(e)],49))}s(Ua,"bgRgb8");h.bgRgb8=Ua;function Na(t,e){return typeof e=="number"?O(t,x([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,x([38,2,ie(e.r),ie(e.g),ie(e.b)],39))}s(Na,"rgb24");h.rgb24=Na;function Ma(t,e){return typeof e=="number"?O(t,x([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,x([48,2,ie(e.r),ie(e.g),ie(e.b)],49))}s(Ma,"bgRgb24");h.bgRgb24=Ma;var Za=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 qa(t){return t.replace(Za,"")}s(qa,"stripColor");h.stripColor=qa;h.colorFunctions=[uo,co,lo,po,go,mo];function Fa(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}s(Fa,"hashCode");function $a(t){let e=Math.abs(Fa(t));return h.colorFunctions[e%h.colorFunctions.length]}s($a,"generateColor");h.generateColor=$a});var yo=qe(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.format=void 0;function Ba(t,e,...n){let r=0,o=n.length,i=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(`
26
+ `).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)?i+=" "+a:i+=" "+t(a);return i}s(Ba,"format");lt.format=Ba});var Io=qe(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.inspect=void 0;function ge(t,e,n,r){let o={seen:[],stylize:Va,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Ga),dt(o,t,o.depth)}s(ge,"inspect");pt.inspect=ge;ge.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]};ge.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Va(t,e){return t}s(Va,"stylizeNoColor");function za(t){return typeof t=="boolean"}s(za,"isBoolean");function Ro(t){return t===void 0}s(Ro,"isUndefined");function Ga(t,e){let n=ge.styles[e];return n?"\x1B["+ge.colors[n][0]+"m"+t+"\x1B["+ge.colors[n][1]+"m":t}s(Ga,"stylizeWithColor");function Dn(t){return typeof t=="function"}s(Dn,"isFunction");function wo(t){return typeof t=="string"}s(wo,"isString");function ja(t){return typeof t=="number"}s(ja,"isNumber");function Po(t){return t===null}s(Po,"isNull");function Eo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Eo,"hasOwn");function kn(t){return Mn(t)&&Zn(t)==="[object RegExp]"}s(kn,"isRegExp");function Mn(t){return typeof t=="object"&&t!==null}s(Mn,"isObject");function Hn(t){return Mn(t)&&(Zn(t)==="[object Error]"||t instanceof Error)}s(Hn,"isError");function bo(t){return Mn(t)&&Zn(t)==="[object Date]"}s(bo,"isDate");function Zn(t){return Object.prototype.toString.call(t)}s(Zn,"objectToString");function Ja(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(Ja,"arrayToHash");function Ka(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)Eo(e,String(a))?i.push(Nn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Nn(t,e,n,r,a,!0))}),i}s(Ka,"formatArray");function Un(t){return"["+Error.prototype.toString.call(t)+"]"}s(Un,"formatError");function dt(t,e,n){if(t.customInspect&&e&&Dn(e.inspect)&&e.inspect!==ge&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return wo(d)||(d=dt(t,d,n)),d}let r=Wa(t,e);if(r)return r;let o=Object.keys(e),i=Ja(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Hn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Un(e);if(o.length===0){if(Dn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(kn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(bo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Hn(e))return Un(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Dn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),kn(e)&&(a=" "+RegExp.prototype.toString.call(e)),bo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Hn(e)&&(a=" "+Un(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return kn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Ka(t,e,n,i,o):l=o.map(function(d){return Nn(t,e,n,i,d,u)}),t.seen.pop(),Ya(l,a,c)}s(dt,"formatValue");function Nn(t,e,n,r,o,i){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")),Eo(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Po(n)?u=dt(t,c.value,null):u=dt(t,c.value,n-1),u.indexOf(`
27
27
  `)>-1&&(i?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):u=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=t.stylize("[Circular]","special")),ho(a)){if(i&&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}s(Nn,"formatProperty");function Ga(t,e){if(ho(e))return t.stylize("undefined","undefined");if(yo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if($a(e))return t.stylize(""+e,"number");if(qa(e))return t.stylize(""+e,"boolean");if(bo(e))return t.stylize("null","null")}s(Ga,"formatPrimitive");function Va(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
32
+ `))):u=t.stylize("[Circular]","special")),Ro(a)){if(i&&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}s(Nn,"formatProperty");function Wa(t,e){if(Ro(e))return t.stylize("undefined","undefined");if(wo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(ja(e))return t.stylize(""+e,"number");if(za(e))return t.stylize(""+e,"boolean");if(Po(e))return t.stylize("null","null")}s(Wa,"formatPrimitive");function Ya(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
34
34
  `)+" "+t.join(`,
35
- `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(Va,"reduceToSingleString")});var Po=Ze(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.format=void 0;var ja=mo(),Ja=wo(),Ka=s((t,...e)=>(0,ja.format)(Ja.inspect,t,e),"format");pt.format=Ka});var ge=Ze(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.debug=se.withoutEnv=se.Debugger=void 0;var Wa=go(),Ya=Po(),gt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Wa.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,Ya.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};se.Debugger=gt;var mt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Eo(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Eo,"extract");var Fe;function Qa(t){t||(t=[]),typeof t=="string"&&(t=Eo(t)),Fe=new mt(t)}s(Qa,"withoutEnv");se.withoutEnv=Qa;function Xa(t){let e=globalThis.DEBUG;Fe||(Fe=new mt(Eo(e)));let n=new gt(Fe,t);return Fe.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(Xa,"debug");se.debug=Xa});var qc={};Vs(qc,{API_KEY:()=>Zo,AWSLoggingPlugin:()=>Jt,AmberfloMeteringInboundPolicy:()=>_i,AmberfloMeteringPolicy:()=>Xt,ApiAuthKeyInboundPolicy:()=>Hi,ApiKeyInboundPolicy:()=>vr,AuditLogDataStaxProvider:()=>Yt,AuditLogPlugin:()=>Qt,Auth0JwtInboundPolicy:()=>Ui,AwsLambdaHandlerExtensions:()=>yi,BasicAuthInboundPolicy:()=>Ni,BasicRateLimitInboundPolicy:()=>kr,CachingInboundPolicy:()=>Mi,ChangeMethodInboundPolicy:()=>Zi,ClearHeadersInboundPolicy:()=>qi,ClearHeadersOutboundPolicy:()=>Fi,ClerkJwtInboundPolicy:()=>$i,CognitoJwtInboundPolicy:()=>Bi,CompositeInboundPolicy:()=>zi,ConfigurationError:()=>f,ContentTypes:()=>ln,ContextData:()=>Ft,CryptoBeta:()=>gn,DataDogLoggingPlugin:()=>Dt,DataDogMetricsPlugin:()=>Kt,DynaTraceLoggingPlugin:()=>zt,DynatraceMetricsPlugin:()=>Wt,FirebaseJwtInboundPolicy:()=>Gi,FormDataToJsonInboundPolicy:()=>Vi,GeoFilterInboundPolicy:()=>ji,GoogleCloudLoggingPlugin:()=>Lt,Handler:()=>$t,HttpProblems:()=>I,HttpStatusCode:()=>bt,JWTScopeValidationInboundPolicy:()=>Ji,KeyValueStore:()=>fn,LokiLoggingPlugin:()=>Gt,LookupResult:()=>Te,MemoryZoneReadThroughCache:()=>M,MockApiInboundPolicy:()=>Wi,MoesifInboundPolicy:()=>ns,OktaJwtInboundPolicy:()=>rs,OpenIdJwtInboundPolicy:()=>N,ProblemResponseFormatter:()=>ae,PropelAuthJwtInboundPolicy:()=>is,RateLimitInboundPolicy:()=>kr,ReadmeMetricsInboundPolicy:()=>ls,RemoveHeadersInboundPolicy:()=>ds,RemoveHeadersOutboundPolicy:()=>ps,RemoveQueryParamsInboundPolicy:()=>gs,ReplaceStringOutboundPolicy:()=>ms,RequestSizeLimitInboundPolicy:()=>hs,RequestValidationInboundPolicy:()=>Nr,RequireOriginInboundPolicy:()=>xs,ResponseSendingEvent:()=>Ie,ResponseSentEvent:()=>xe,Router:()=>Ce,SYSTEM_LOGGER:()=>je,SchemaBasedRequestValidation:()=>Is,ServiceProviderImpl:()=>dn,SetBodyInboundPolicy:()=>Os,SetHeadersInboundPolicy:()=>vs,SetHeadersOutboundPolicy:()=>Ts,SetQueryParamsInboundPolicy:()=>Cs,SetStatusOutboundPolicy:()=>As,SleepInboundPolicy:()=>Ls,SumoLogicLoggingPlugin:()=>Vt,SupabaseJwtInboundPolicy:()=>Ss,SystemLogMap:()=>A,SystemRouteName:()=>ne,UpstreamAzureAdServiceAuthInboundPolicy:()=>_s,UpstreamFirebaseAdminAuthInboundPolicy:()=>ks,UpstreamFirebaseUserAuthInboundPolicy:()=>Hs,UpstreamGcpJwtInboundPolicy:()=>Us,UpstreamGcpServiceAuthInboundPolicy:()=>Ms,VALID_COMPATIBILITY_DATES:()=>jr,VMWareLogInsightLoggingPlugin:()=>jt,ValidateJsonSchemaInbound:()=>Zs,ZoneCache:()=>oe,ZuploRequest:()=>_,awsLambdaHandler:()=>bi,environment:()=>nt,getIdForParameterSchema:()=>an,getIdForRefSchema:()=>bs,getIdForRequestBodySchema:()=>un,getRawOperationDataIdentifierName:()=>ys,httpStatuses:()=>Rt,isRestrictedEnvVariableName:()=>or,isZuploReadableEnvVariableName:()=>ir,openApiSpecHandler:()=>Ri,originalFetch:()=>Ae,purgeGatewayCache:()=>si,redirectHandler:()=>wi,sanitizedIdentifierName:()=>de,serialize:()=>ht,setMoesifContext:()=>ts,urlForwardHandler:()=>Pi,urlRewriteHandler:()=>Ei,webSocketHandler:()=>Ii,webSocketPipelineHandler:()=>vi});module.exports=js(qc);var S=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},E=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends E{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},at=class extends E{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var b=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new S("Environment has not been initialized");return this.#e}constructor(e,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}build;runtime;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.dev"}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 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"}};Function.prototype.toString=function(){return"[native code]"};var ut=globalThis,Gr=ut.caches;if(Gr){let t=Gr.open;ut.caches.open=function(e){let n=b.instance.deploymentName??b.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete ut.caches.default,Object.freeze(ut.caches)}var Vr=new Map,yn=class{static{s(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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}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{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Vr.get(e);r||(r=new yn(n),Vr.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 bn="__zuplo-expiry-header",oe=class{static{s(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 i=o.headers.get(bn);if(!i){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(i);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(bn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.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(bn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}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 M=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new we(r),this.#n=new oe(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};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var jr=Object.freeze(["2023-03-14"]);var Jr="zuplo-request-id",qe="zp-rid",Kr="zp-body-removed",Pe="cf-ray",Rn="cf-ipcity",wn="cf-ipcontinent",Pn="cf-ipcountry",En="cf-iplongitude",In="cf-iplatitude",Wr="zp-ipcity",Yr="zp-ipcontinent",Qr="zp-ipcountry",Xr="zp-iplongitude",eo="zp-iplatitude",to="true-client-ip",xn="zp-asn",On="zp-asorg",vn="zp-colo",Tn="zp-postalcode",Cn="zp-metrocode",An="zp-region",Ln="zp-regioncode",Sn="zp-timezone",no=[Rn,wn,Pn,En,In,xn,On,vn,Tn,Cn,An,Ln,Sn],ro=["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"];var Yo=Re(ge());var $e=class t{static{s(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(i){throw new E("Error in custom 'problemResponseFormat'",{cause:i})}})}},ae=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await $e.problemResponseFormat(e,n,r)}};var me=class{static{s(this,"RuntimePlugin")}},Be=class extends me{static{s(this,"InitializableRuntimePlugin")}},ze={},Ee=[],Io=[],xo=[],Oo=[];var ft={addPlugin(t){Ee.push(t)},addRequestHook(t){Io.push(t)},addResponseSendingHook(t){xo.push(t)},addResponseSendingFinalHook(t){Oo.push(t)}},vo=s(async(t,e)=>{let n=t;for(let r of Io)if(n=await r(n,e),n instanceof Response)return n;return n},"invokeOnRequestExtensions"),To=s(async(t,e,n)=>{let r=t;for(let o of xo)r=await o(t,e,n);return r},"invokeOnResponseSendingExtensions"),Co=s(async(t,e,n)=>{for(let r of Oo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Ao(t=()=>Promise.resolve()){await t(ft),ze.value=ft;let e=Ee.filter(n=>n instanceof Be);for(let n of e)await n.initialize(ft);$e.setProblemResponseFormat(ft.problemResponseFormat)}s(Ao,"initializeRuntime");var U=class{static{s(this,"Pipeline")}constructor(e,n,r){this.execute=this.#t(e,n,r)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=(e,n,r)=>async(o,i)=>{let a=[...e],u=s(async y=>{let P=a.pop();return P?P(o,i,r,u):await this.#e(async v=>{let C=await n(v,i);return eu(C)},r)(y,i)},"nextPipe"),l=await u(o),d=new Ie(o,l);i.dispatchEvent(d);let p=Z.getContextExtensions(i),R=p.latestRequest,m;try{m=await d.mutableResponse}catch(y){return i.log.error(y),r.errorHandler(o,i,y)}try{m=await p.onResponseSending(m,R,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),r.errorHandler(o,i,y)}try{m=await To(m,R,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),r.errorHandler(o,i,y)}i.dispatchEvent(new xe(o,m));try{await p.onResponseSendingFinal(l,R,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await Co(l,R,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return m}};function eu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(ht(t),{headers:{"content-type":"application/json"}})}s(eu,"resultToResponse");var ue=class extends me{static{s(this,"MetricsPlugin")}};var A=class t{static{s(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 S(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var T=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#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&&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 yt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=b.instance.loggingId,this.#e=e,this.#t=new T("ellie-metrics-transport",10,this.dispatchFunction,A.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:i}=b.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":b.instance.deploymentName??"unknown","user-agent":b.instance.systemUserAgent}});if(!u.ok){let c=await u.text();A.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Ge.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ge={name:"__system-no-version",pathPrefix:""};var z=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Pe)??void 0,c=t.headers.get(to)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=Z.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,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:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new yt(e)),Ee.forEach(y=>{if(y instanceof ue){let P=y.getTransport();m.push(P)}}),m.forEach(y=>{y.pushMetrics(R,e)}),a},"metricsProcessor");var ne=(u=>(u.Build="build-data",u.CorsPreflight="cors-preflight",u.DeveloperPortal="developer-portal",u.DeveloperPortalLegacy="developer-portal-legacy",u.EmptyGatewayCatchall="empty-gateway-catchall",u.Ping="ping",u.UnmatchedPath="unmatched-path",u))(ne||{});var qn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return I.notFound(i,a);let l=b.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&A.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new U([z],n,e),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var bt=(g=>(g[g.CONTINUE=100]="CONTINUE",g[g.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",g[g.PROCESSING=102]="PROCESSING",g[g.EARLY_HINTS=103]="EARLY_HINTS",g[g.OK=200]="OK",g[g.CREATED=201]="CREATED",g[g.ACCEPTED=202]="ACCEPTED",g[g.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",g[g.NO_CONTENT=204]="NO_CONTENT",g[g.RESET_CONTENT=205]="RESET_CONTENT",g[g.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",g[g.MULTI_STATUS=207]="MULTI_STATUS",g[g.ALREADY_REPORTED=208]="ALREADY_REPORTED",g[g.IM_USED=226]="IM_USED",g[g.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",g[g.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",g[g.FOUND=302]="FOUND",g[g.SEE_OTHER=303]="SEE_OTHER",g[g.NOT_MODIFIED=304]="NOT_MODIFIED",g[g.USE_PROXY=305]="USE_PROXY",g[g.SWITCH_PROXY=306]="SWITCH_PROXY",g[g.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",g[g.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",g[g.BAD_REQUEST=400]="BAD_REQUEST",g[g.UNAUTHORIZED=401]="UNAUTHORIZED",g[g.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",g[g.FORBIDDEN=403]="FORBIDDEN",g[g.NOT_FOUND=404]="NOT_FOUND",g[g.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",g[g.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",g[g.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",g[g.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",g[g.CONFLICT=409]="CONFLICT",g[g.GONE=410]="GONE",g[g.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",g[g.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",g[g.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",g[g.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",g[g.URI_TOO_LONG=414]="URI_TOO_LONG",g[g.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",g[g.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",g[g.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",g[g.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",g[g.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",g[g.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",g[g.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",g[g.LOCKED=423]="LOCKED",g[g.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",g[g.TOO_EARLY=425]="TOO_EARLY",g[g.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",g[g.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",g[g.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",g[g.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",g[g.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",g[g.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",g[g.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",g[g.BAD_GATEWAY=502]="BAD_GATEWAY",g[g.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",g[g.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",g[g.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",g[g.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",g[g.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",g[g.LOOP_DETECTED=508]="LOOP_DETECTED",g[g.NOT_EXTENDED=510]="NOT_EXTENDED",g[g.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",g))(bt||{}),Lo={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"};function tu(t){return`${new URL(t.url).pathname}`}s(tu,"instance");function nu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:b.instance.build.BUILD_ID},r=t.headers.get(Pe);return r&&(n.rayId=r),n}s(nu,"trace");var ru=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:tu(e),trace:nu(e,n),...r},additionalHeaders:o,statusText:Rt[t.status]}),"merge"),Fn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ae.format(e,n,r):ae.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Lo[e],...n}}},I=class extends Fn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=ru(this.getProblemFromStatus(e),n,r,o,i);return ae.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 Pt=s((t,e)=>{if(e!==null)if(t){let n=wt(t).split(",");if(n.find(u=>u==="*"))return e;let o=n.map(u=>u.trim().toLowerCase()),i=e.toLowerCase();return o.find(u=>u===i)}else return},"findMatchingOrigin"),Et=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=wt(t.allowedHeaders)),t.allowedMethods&&(n["access-control-allow-methods"]=wt(t.allowedMethods)),t.exposeHeaders&&(n["access-control-expose-headers"]=wt(t.exposeHeaders));let r=t.allowCredentials?.toString()??void 0;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders"),wt=s(t=>Array.isArray(t)?t.map(e=>e.trim()).join(", "):t,"normalizePolicies");var $n=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(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 I.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return I.notFound(a,u);let m=R.routeConfiguration,y=ou(l,d,p,m,n);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):I.notFound(a,u)},"optionsHandler"),o=new U([z],r,e),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),ou=s((t,e,n,r,o)=>{let i={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 i;let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section`);let u=Pt(a.allowedOrigins,n);return u?{isValid:!0,headers:Et(a,u)}:i},"validateAndBuildResponseHeaders");var So=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new U([z],n,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 Bn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),_o=s((t,e)=>{let n=s(async(o,i)=>{let a=ze.value?.notFoundHandler;if(a){let u=Z.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return I.notFound(o,i)},"notFoundHandler"),r=new U([z],n,e);t.addRoute(Bn,r.execute)},"registerNotMatchedHandler");var iu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Do=s(t=>{iu.forEach(e=>t.delete(e))},"stripCorsHeaders"),It=s(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 Do(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new S(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=su(o,n.routeData.corsPolicies),u=au(t,a),c=new Headers(i.headers);return Do(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),su=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:["*"],allowedOrigins:["*"],allowedMethods:t.methods,exposeHeaders:["*"],allowCredentials:!0,maxAge:600};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),au=s((t,e)=>{let n=Pt(e.allowedOrigins,t.headers.get("origin"));return n?Et(e,n):{}},"getCorsHeaders");var zn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new U([It],n,e),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function xt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&xt(n)}return Object.freeze(t)}s(xt,"deepFreeze");var _=class t extends Request{static{s(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){this.#e={};let e=new URL(this.url).searchParams;for(let[n,r]of e.entries())this.#e[n]=r}return xt(this.#e)}get params(){return xt(this.#t)}user};function Ve(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new f(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Ve,"getInboundPolicyHandlerAndOptions");function uu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(uu,"getOutboundPolicyHandlerAndOptions");var Gn=s(t=>async(e,n)=>{let r=Z.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),cu=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Ot=s(async(t,e,n,r)=>{let o=Ve(e.route,n.routeData.policies),i=uu(e.route,n.routeData.policies),a=Gn(o);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await r(u),l=cu(i);return c.ok?l(c,t,e):c}catch(u){return e.log.error(u),n.errorHandler(t,e,u)}},"policyProcessor");function ko(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||lu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,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]=du(l,o)}i=u+1}return n}s(ko,"parse");function lu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(lu,"decode");function du(t,e){try{return e(t)}catch{return t}}s(du,"tryDecode");function Ho(t,e){try{let n=/v\d+(-\d+)?/g,o=ko(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Ho,"devPortalBaseURL");var Uo="/__zuplo/dev-portal",pu="dev-portal-id",gu="dev-portal-host",mu="zp-account",fu="zp-project",hu="dev-portal-build",yu=`
35
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(Ya,"reduceToSingleString")});var xo=qe(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.format=void 0;var Qa=yo(),Xa=Io(),eu=s((t,...e)=>(0,Qa.format)(Xa.inspect,t,e),"format");gt.format=eu});var me=qe(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.debug=se.withoutEnv=se.Debugger=void 0;var tu=ho(),nu=xo(),mt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,tu.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,nu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};se.Debugger=mt;var ft=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Oo(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Oo,"extract");var $e;function ru(t){t||(t=[]),typeof t=="string"&&(t=Oo(t)),$e=new ft(t)}s(ru,"withoutEnv");se.withoutEnv=ru;function ou(t){let e=globalThis.DEBUG;$e||($e=new ft(Oo(e)));let n=new mt($e,t);return $e.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(ou,"debug");se.debug=ou});var zc={};Ys(zc,{API_KEY:()=>Wo,AWSLoggingPlugin:()=>Jt,AmberfloMeteringInboundPolicy:()=>Ni,AmberfloMeteringPolicy:()=>Xt,ApiAuthKeyInboundPolicy:()=>qi,ApiKeyInboundPolicy:()=>Ar,AuditLogDataStaxProvider:()=>Yt,AuditLogPlugin:()=>Qt,Auth0JwtInboundPolicy:()=>Fi,AwsLambdaHandlerExtensions:()=>xi,BasicAuthInboundPolicy:()=>$i,BasicRateLimitInboundPolicy:()=>Nr,CachingInboundPolicy:()=>Bi,ChangeMethodInboundPolicy:()=>Vi,ClearHeadersInboundPolicy:()=>zi,ClearHeadersOutboundPolicy:()=>Gi,ClerkJwtInboundPolicy:()=>ji,CognitoJwtInboundPolicy:()=>Ji,CompositeInboundPolicy:()=>Ki,ConfigurationError:()=>f,ContentTypes:()=>ln,ContextData:()=>Ft,CryptoBeta:()=>gn,DataDogLoggingPlugin:()=>Dt,DataDogMetricsPlugin:()=>Kt,DynaTraceLoggingPlugin:()=>Vt,DynatraceMetricsPlugin:()=>Wt,FirebaseJwtInboundPolicy:()=>Wi,FormDataToJsonInboundPolicy:()=>Yi,GeoFilterInboundPolicy:()=>Qi,GoogleCloudLoggingPlugin:()=>Lt,Handler:()=>$t,HttpProblems:()=>I,HttpStatusCode:()=>Rt,JWTScopeValidationInboundPolicy:()=>Xi,KeyValueStore:()=>fn,LokiLoggingPlugin:()=>zt,LookupResult:()=>Ce,MemoryZoneReadThroughCache:()=>M,MockApiInboundPolicy:()=>ts,MoesifInboundPolicy:()=>as,OktaJwtInboundPolicy:()=>us,OpenIdJwtInboundPolicy:()=>N,ProblemResponseFormatter:()=>ae,PropelAuthJwtInboundPolicy:()=>ls,RateLimitInboundPolicy:()=>Nr,ReadmeMetricsInboundPolicy:()=>fs,RemoveHeadersInboundPolicy:()=>hs,RemoveHeadersOutboundPolicy:()=>ys,RemoveQueryParamsInboundPolicy:()=>bs,ReplaceStringOutboundPolicy:()=>Rs,RequestSizeLimitInboundPolicy:()=>Ps,RequestValidationInboundPolicy:()=>qr,RequireOriginInboundPolicy:()=>As,ResponseSendingEvent:()=>xe,ResponseSentEvent:()=>Oe,Router:()=>Ae,SYSTEM_LOGGER:()=>We,SchemaBasedRequestValidation:()=>Cs,ServiceProviderImpl:()=>dn,SetBodyInboundPolicy:()=>Ls,SetHeadersInboundPolicy:()=>Ss,SetHeadersOutboundPolicy:()=>_s,SetQueryParamsInboundPolicy:()=>Ds,SetStatusOutboundPolicy:()=>ks,SleepInboundPolicy:()=>Hs,SumoLogicLoggingPlugin:()=>Gt,SupabaseJwtInboundPolicy:()=>Us,SystemLogMap:()=>A,SystemRouteName:()=>ne,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ns,UpstreamFirebaseAdminAuthInboundPolicy:()=>Zs,UpstreamFirebaseUserAuthInboundPolicy:()=>qs,UpstreamGcpJwtInboundPolicy:()=>Fs,UpstreamGcpServiceAuthInboundPolicy:()=>Bs,VALID_COMPATIBILITY_DATES:()=>Wr,VMWareLogInsightLoggingPlugin:()=>jt,ValidateJsonSchemaInbound:()=>Vs,ZoneCache:()=>oe,ZuploRequest:()=>_,awsLambdaHandler:()=>Oi,environment:()=>rt,getIdForParameterSchema:()=>an,getIdForRefSchema:()=>Is,getIdForRequestBodySchema:()=>un,getRawOperationDataIdentifierName:()=>Es,httpStatuses:()=>wt,isRestrictedEnvVariableName:()=>ar,isZuploReadableEnvVariableName:()=>ur,openApiSpecHandler:()=>vi,originalFetch:()=>Le,purgeGatewayCache:()=>gi,redirectHandler:()=>Ti,sanitizedIdentifierName:()=>pe,serialize:()=>yt,setMoesifContext:()=>ss,urlForwardHandler:()=>Ci,urlRewriteHandler:()=>Ai,webSocketHandler:()=>Li,webSocketPipelineHandler:()=>Di});module.exports=Qs(zc);var S=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},E=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends E{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},ut=class extends E{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var b=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new S("Environment has not been initialized");return this.#e}constructor(e,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}build;runtime;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.dev"}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 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"}};Function.prototype.toString=function(){return"[native code]"};var ct=globalThis,Jr=ct.caches;if(Jr){let t=Jr.open;ct.caches.open=function(e){let n=b.instance.deploymentName??b.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete ct.caches.default,Object.freeze(ct.caches)}var Kr=new Map,yn=class{static{s(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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}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)})}},Pe=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Kr.get(e);r||(r=new yn(n),Kr.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 bn="__zuplo-expiry-header",oe=class{static{s(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 i=o.headers.get(bn);if(!i){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(i);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(bn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.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(bn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}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 M=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Pe(r),this.#n=new oe(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};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var Wr=Object.freeze(["2023-03-14"]);var Yr="zuplo-request-id",Fe="zp-rid",Qr="zp-body-removed",Ee="cf-ray",Rn="cf-ipcity",wn="cf-ipcontinent",Pn="cf-ipcountry",En="cf-iplongitude",In="cf-iplatitude",Xr="zp-ipcity",eo="zp-ipcontinent",to="zp-ipcountry",no="zp-iplongitude",ro="zp-iplatitude",oo="true-client-ip",xn="zp-asn",On="zp-asorg",vn="zp-colo",Tn="zp-postalcode",Cn="zp-metrocode",An="zp-region",Ln="zp-regioncode",Sn="zp-timezone",io=[Rn,wn,Pn,En,In,xn,On,vn,Tn,Cn,An,Ln,Sn],so=["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"];var oi=we(me());var Be=class t{static{s(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(i){throw new E("Error in custom 'problemResponseFormat'",{cause:i})}})}},ae=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await Be.problemResponseFormat(e,n,r)}};var fe=class{static{s(this,"RuntimePlugin")}},Ve=class extends fe{static{s(this,"InitializableRuntimePlugin")}},ze={},Ie=[],vo=[],To=[],Co=[];var ht={addPlugin(t){Ie.push(t)},addRequestHook(t){vo.push(t)},addResponseSendingHook(t){To.push(t)},addResponseSendingFinalHook(t){Co.push(t)}},Ao=s(async(t,e)=>{let n=t;for(let r of vo)if(n=await r(n,e),n instanceof Response)return n;return n},"invokeOnRequestExtensions"),Lo=s(async(t,e,n)=>{let r=t;for(let o of To)r=await o(t,e,n);return r},"invokeOnResponseSendingExtensions"),So=s(async(t,e,n)=>{for(let r of Co)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function _o(t=()=>Promise.resolve()){await t(ht),ze.value=ht;let e=Ie.filter(n=>n instanceof Ve);for(let n of e)await n.initialize(ht);Be.setProblemResponseFormat(ht.problemResponseFormat)}s(_o,"initializeRuntime");var U=class{static{s(this,"Pipeline")}constructor(e,n,r){this.execute=this.#t(e,n,r)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=(e,n,r)=>async(o,i)=>{let a=[...e],u=s(async y=>{let P=a.pop();return P?P(o,i,r,u):await this.#e(async v=>{let C=await n(v,i);return iu(C)},r)(y,i)},"nextPipe"),l=await u(o),d=new xe(o,l);i.dispatchEvent(d);let p=Z.getContextExtensions(i),R=p.latestRequest,m;try{m=await d.mutableResponse}catch(y){return i.log.error(y),r.errorHandler(o,i,y)}try{m=await p.onResponseSending(m,R,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),r.errorHandler(o,i,y)}try{m=await Lo(m,R,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),r.errorHandler(o,i,y)}i.dispatchEvent(new Oe(o,m));try{await p.onResponseSendingFinal(l,R,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await So(l,R,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return m}};function iu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(yt(t),{headers:{"content-type":"application/json"}})}s(iu,"resultToResponse");var ue=class extends fe{static{s(this,"MetricsPlugin")}};var A=class t{static{s(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 S(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var T=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#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&&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 bt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=b.instance.loggingId,this.#e=e,this.#t=new T("ellie-metrics-transport",10,this.dispatchFunction,A.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:i}=b.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":b.instance.deploymentName??"unknown","user-agent":b.instance.systemUserAgent}});if(!u.ok){let c=await u.text();A.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Ge.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ge={name:"__system-no-version",pathPrefix:""};var V=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Ee)??void 0,c=t.headers.get(oo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=Z.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,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:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new bt(e)),Ie.forEach(y=>{if(y instanceof ue){let P=y.getTransport();m.push(P)}}),m.forEach(y=>{y.pushMetrics(R,e)}),a},"metricsProcessor");var ne=(u=>(u.Build="build-data",u.CorsPreflight="cors-preflight",u.DeveloperPortal="developer-portal",u.DeveloperPortalLegacy="developer-portal-legacy",u.EmptyGatewayCatchall="empty-gateway-catchall",u.Ping="ping",u.UnmatchedPath="unmatched-path",u))(ne||{});var qn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return I.notFound(i,a);let l=b.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&A.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new U([V],n,e),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var Rt=(g=>(g[g.CONTINUE=100]="CONTINUE",g[g.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",g[g.PROCESSING=102]="PROCESSING",g[g.EARLY_HINTS=103]="EARLY_HINTS",g[g.OK=200]="OK",g[g.CREATED=201]="CREATED",g[g.ACCEPTED=202]="ACCEPTED",g[g.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",g[g.NO_CONTENT=204]="NO_CONTENT",g[g.RESET_CONTENT=205]="RESET_CONTENT",g[g.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",g[g.MULTI_STATUS=207]="MULTI_STATUS",g[g.ALREADY_REPORTED=208]="ALREADY_REPORTED",g[g.IM_USED=226]="IM_USED",g[g.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",g[g.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",g[g.FOUND=302]="FOUND",g[g.SEE_OTHER=303]="SEE_OTHER",g[g.NOT_MODIFIED=304]="NOT_MODIFIED",g[g.USE_PROXY=305]="USE_PROXY",g[g.SWITCH_PROXY=306]="SWITCH_PROXY",g[g.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",g[g.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",g[g.BAD_REQUEST=400]="BAD_REQUEST",g[g.UNAUTHORIZED=401]="UNAUTHORIZED",g[g.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",g[g.FORBIDDEN=403]="FORBIDDEN",g[g.NOT_FOUND=404]="NOT_FOUND",g[g.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",g[g.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",g[g.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",g[g.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",g[g.CONFLICT=409]="CONFLICT",g[g.GONE=410]="GONE",g[g.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",g[g.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",g[g.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",g[g.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",g[g.URI_TOO_LONG=414]="URI_TOO_LONG",g[g.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",g[g.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",g[g.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",g[g.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",g[g.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",g[g.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",g[g.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",g[g.LOCKED=423]="LOCKED",g[g.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",g[g.TOO_EARLY=425]="TOO_EARLY",g[g.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",g[g.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",g[g.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",g[g.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",g[g.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",g[g.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",g[g.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",g[g.BAD_GATEWAY=502]="BAD_GATEWAY",g[g.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",g[g.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",g[g.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",g[g.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",g[g.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",g[g.LOOP_DETECTED=508]="LOOP_DETECTED",g[g.NOT_EXTENDED=510]="NOT_EXTENDED",g[g.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",g))(Rt||{}),Do={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"};function su(t){return`${new URL(t.url).pathname}`}s(su,"instance");function au(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:b.instance.build.BUILD_ID},r=t.headers.get(Ee);return r&&(n.rayId=r),n}s(au,"trace");var uu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:su(e),trace:au(e,n),...r},additionalHeaders:o,statusText:wt[t.status]}),"merge"),Fn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ae.format(e,n,r):ae.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Do[e],...n}}},I=class extends Fn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=uu(this.getProblemFromStatus(e),n,r,o,i);return ae.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:cu}=Object.prototype,{propertyIsEnumerable:lu}=Object.prototype;function $n(t){return cu.call(t)}s($n,"toString");function ce(t){return typeof t=="string"}s(ce,"isString");function ko(t){return ce(t)&&t!==""}s(ko,"isNonEmptyString");function Ho(t){return $n(t)==="[object RegExp]"}s(Ho,"isRegexp");function Uo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>lu.call(t,e))]}s(Uo,"getOwnEnumerableKeys");function je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(je,"isObject");function Bn(t){return typeof t=="number"&&!isNaN(t)}s(Bn,"isNumber");function Vn(t){return t===!0||t===!1}s(Vn,"isBoolean");function No(t){return typeof t>"u"}s(No,"isUndefined");function Mo(t){return No(t)||t===null}s(Mo,"isUndefinedOrNull");function Je(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Je,"isErrorLike");var Zo=new Map;function qo(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Zo.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Zo.set(t,r),r}s(qo,"statusCodesStringToNumberArray");function he(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new E(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(he,"getValueFromRequestUser");function zn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new f("Received an array that contains non-string values.");return t}if(ce(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new f(`Expected type of string, received type '${typeof t}'`)}s(zn,"parseValueToStringArray");function Fo(t){if(t==null)return[];if(!Array.isArray(t))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!je(n))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!ko(n.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Bn(n.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Vn(n.allowCredentials))throw new f("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=Gn(n,"allowedHeaders"),o=Gn(n,"allowedMethods"),i=Gn(n,"exposeHeaders"),a;try{a=zn(n.allowedOrigins)}catch(c){throw new f(`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:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(Fo,"parseCorsPolicies");function Gn(t,e){let n;if(t[e]!==void 0)try{n=zn(t[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Gn,"parseOptionalProperty");var Pt=s((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"),Et=s((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 jn=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(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 I.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return I.notFound(a,u);let m=R.routeConfiguration,y=du(l,d,p,m,n);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&u.log.warn(y.error),I.notFound(a,u))},"optionsHandler"),o=new U([V],r,e),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),du=s((t,e,n,r,o)=>{let i={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{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Pt(a.allowedOrigins,n);return u?{isValid:!0,headers:Et(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var $o=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new U([V],n,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 Jn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Bo=s((t,e)=>{let n=s(async(o,i)=>{let a=ze.value?.notFoundHandler;if(a){let u=Z.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return I.notFound(o,i)},"notFoundHandler"),r=new U([V],n,e);t.addRoute(Jn,r.execute)},"registerNotMatchedHandler");var pu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Vo=s(t=>{pu.forEach(e=>t.delete(e))},"stripCorsHeaders"),It=s(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 Vo(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new S(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=gu(o,n.routeData.corsPolicies),u=mu(t,a),c=new Headers(i.headers);return Vo(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),gu=s((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 f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),mu=s((t,e)=>{let n=Pt(e.allowedOrigins,t.headers.get("origin"));return n?Et(e,n):{}},"getCorsHeaders");var Kn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new U([It],n,e),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function xt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&xt(n)}return Object.freeze(t)}s(xt,"deepFreeze");var _=class t extends Request{static{s(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){this.#e={};let e=new URL(this.url).searchParams;for(let[n,r]of e.entries())this.#e[n]=r}return xt(this.#e)}get params(){return xt(this.#t)}user};function Ke(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new f(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Ke,"getInboundPolicyHandlerAndOptions");function fu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(fu,"getOutboundPolicyHandlerAndOptions");var Wn=s(t=>async(e,n)=>{let r=Z.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),hu=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new f(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Ot=s(async(t,e,n,r)=>{let o=Ke(e.route,n.routeData.policies),i=fu(e.route,n.routeData.policies),a=Wn(o);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await r(u),l=hu(i);return c.ok?l(c,t,e):c}catch(u){return e.log.error(u),n.errorHandler(t,e,u)}},"policyProcessor");function zo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||yu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,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]=bu(l,o)}i=u+1}return n}s(zo,"parse");function yu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(yu,"decode");function bu(t,e){try{return e(t)}catch{return t}}s(bu,"tryDecode");function Go(t,e){try{let n=/v\d+(-\d+)?/g,o=zo(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Go,"devPortalBaseURL");var jo="/__zuplo/dev-portal",Ru="dev-portal-id",wu="dev-portal-host",Pu="zp-account",Eu="zp-project",Iu="dev-portal-build",xu=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,18 +46,18 @@
46
46
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
47
47
  </body>
48
48
  </html>
49
- `,No=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=b.instance.deploymentName,o=b.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(b.instance.isLocalDevelopment)return new Response(yu,{headers:{"content-type":"text/html"}});if(!r)return I.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Ho(o,c.headers),R=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:y,body:P}=c;return b.instance.build.ACCOUNT_NAME&&m.set(mu,b.instance.build.ACCOUNT_NAME),b.instance.build.PROJECT_NAME&&m.set(fu,b.instance.build.PROJECT_NAME),m.set(pu,r),m.set(gu,d.host),m.set(hu,b.instance.build.BUILD_ID),await fetch(R.toString(),{headers:m,method:y,body:P,redirect:"manual"})},"devPortalRoute"),a=new U([z,Ot],i,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"),Mo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(Uo.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new U([z],r,e),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Uo}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Wo=Re(ge());var je="system-logger",Zo="api-key";var Vn=0,Je=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){Vn>=Number.MAX_SAFE_INTEGER&&(Vn=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Vn++};this.#t[e](u,a)}};var H=class extends me{static{s(this,"LogPlugin")}};var vt=class{static{s(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 Ke=class{static{s(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{toString:bu}=Object.prototype,{propertyIsEnumerable:Ru}=Object.prototype;function jn(t){return bu.call(t)}s(jn,"toString");function We(t){return typeof t=="string"}s(We,"isString");function qo(t){return jn(t)==="[object RegExp]"}s(qo,"isRegexp");function Fo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Ru.call(t,e))]}s(Fo,"getOwnEnumerableKeys");function Jn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Jn,"isObject");function $o(t){return typeof t>"u"}s($o,"isUndefined");function Bo(t){return $o(t)||t===null}s(Bo,"isUndefinedOrNull");function Ye(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ye,"isErrorLike");var wu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Pu=new Map(wu);var Eu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Kn=Symbol(".toJSON was called"),Iu=s(t=>{t[Kn]=!0;let e=t.toJSON();return delete t[Kn],e},"toJSON"),xu=s(t=>Pu.get(t)??Error,"getErrorConstructor"),zo=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&Ye(t)){let l=xu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Kn]!==!0)return Iu(t);let c=s(l=>zo({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,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])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of Eu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ye(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function q(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?zo({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(q,"serializeError");var Ou=/file:\/\/\/(.*?)\/dist\//g,vu=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Tu="at async Event.respondWith";function Go(t){return typeof t!="string"?t:t.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Ou,"").replaceAll(vu,"").replaceAll(Tu,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
- `)}s(Go,"cleanStack");function Tt(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
49
+ `,Jo=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=b.instance.deploymentName,o=b.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(b.instance.isLocalDevelopment)return new Response(xu,{headers:{"content-type":"text/html"}});if(!r)return I.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Go(o,c.headers),R=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:y,body:P}=c;return b.instance.build.ACCOUNT_NAME&&m.set(Pu,b.instance.build.ACCOUNT_NAME),b.instance.build.PROJECT_NAME&&m.set(Eu,b.instance.build.PROJECT_NAME),m.set(Ru,r),m.set(wu,d.host),m.set(Iu,b.instance.build.BUILD_ID),await fetch(R.toString(),{headers:m,method:y,body:P,redirect:"manual"})},"devPortalRoute"),a=new U([V,Ot],i,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"),Ko=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(jo.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new U([V],r,e),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${jo}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ri=we(me());var We="system-logger",Wo="api-key";var Yn=0,Ye=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){Yn>=Number.MAX_SAFE_INTEGER&&(Yn=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Yn++};this.#t[e](u,a)}};var H=class extends fe{static{s(this,"LogPlugin")}};var vt=class{static{s(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 Qe=class{static{s(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 Ou=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),vu=new Map(Ou);var Tu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Qn=Symbol(".toJSON was called"),Cu=s(t=>{t[Qn]=!0;let e=t.toJSON();return delete t[Qn],e},"toJSON"),Au=s(t=>vu.get(t)??Error,"getErrorConstructor"),Yo=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&Je(t)){let l=Au(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Qn]!==!0)return Cu(t);let c=s(l=>Yo({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,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])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of Tu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Je(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function q(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Yo({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(q,"serializeError");var Lu=/file:\/\/\/(.*?)\/dist\//g,Su=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,_u="at async Event.respondWith";function Qo(t){return typeof t!="string"?t:t.split(`
50
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Lu,"").replaceAll(Su,"").replaceAll(_u,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
+ `)}s(Qo,"cleanStack");function Tt(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
53
53
  `,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 R=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let y=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return y.length<=u.inlineCharacterLimit?y:m.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).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"||qo(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 m="["+p.newline+a.map((y,P)=>{let w=a.length-1===P?p.newline:","+p.newlineOrSpace,v=i(y,u,c+d,l+1);return u.transform&&(v=u.transform(a,P,v)),p.indent+v+w}).join("")+p.pad+"]";return r.pop(),R(m)}if(Jn(a)){let m=Fo(a);if(u.filter&&(m=m.filter(P=>u.filter?.(a,P))),m.length===0)return"{}";r.push(a);let y="{"+p.newline+m.map((P,w)=>{let v=m.length-1===w?p.newline:","+p.newlineOrSpace,C=typeof P=="symbol",D=!C&&/^[a-z$_][$\w]*$/i.test(P),L=C||D?P:i(P,u,"",l+1),B=i(a[P],u,c+d,l+1);return u.transform&&(B=u.transform(a,P,B)),p.indent+String(L)+": "+B+v}).join("")+p.pad+"}";return r.pop(),R(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(Tt,"stringifyObject");function ce(t){return t.map(e=>q(e))}s(ce,"makeErrorsSerializable");function Oe(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:re(q(e))}s(Oe,"extractBestMessage");function Vo(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Ye(n))if(n.stack)e.push(n.stack);else{let r=Tt(q(n));e.push(r)}else if(typeof n=="object"){let r=Tt(n);e.push(r)}else{let r=Wn(n);e.push(r)}}),e.join(`
56
- `)}s(Vo,"messagesToMultilineText");function re(t){return typeof t=="string"?t:JSON.stringify(t)}s(re,"stringifyNonString");function Wn(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"?jn(t):"unknown"}s(Wn,"stringifyNonStringToText");var Ct=require("jose");async function ve(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(ve,"fetchRetry");async function ee({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ct.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ee,"getTokenFromGcpServiceAccount");async function jo(t,e,n){return Jo(t,{token:e,returnSecureToken:!0},n)}s(jo,"exchangeFirebaseJwtForIdToken");async function At(t,e,n){return Jo(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(At,"exchangeGgpJwtForIdToken");async function Jo(t,e,n){let r=await ve(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new E({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Jo,"fetchToken");var G=class t{static{s(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(0,Ct.importPKCS8)(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 Lt=class extends H{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Qe(this.options)}},Cu="https://logging.googleapis.com/v2/entries:write?alt=json",Yn={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Qe=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=b.instance.loggingEnvironmentType,this.#i=b.instance.loggingEnvironmentStage,this.#r=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:ce(e.messages)};this.#t||(this.#t=await G.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Yn[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&&(i.labels.rayId=e.rayId);let a=Oe(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await G.init(this.#e));let n=await ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Cu,{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 T("google-log-transport",1,this.dispatchFunction)};var St="gcp";function _t(t){let e={allMessages:ce(t.messages)},n="zuplo-production",r=Oe(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:Yn[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}s(_t,"gcpLogFormat");var Xe=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===St){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_t(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 Dt=class extends H{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new et(this.options)}},Qn="__ddtags",Xn="__ddattr",er=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Au=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(er(r)):n.push(`${er(r)}:${er(o.toString())}`)}),n.join(",")},"formatTags"),et=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[Qn];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[Qn]!==void 0);a>-1&&(Object.assign(r,i[a][Qn]),i.splice(a,1));let u={},c=n.custom[Xn];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[Xn]!==void 0);l>-1&&(Object.assign(u,i[l][Xn]),i.splice(l,1));let d=ce(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Oe(d),service:e.loggingId,ddtags:Au(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),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 T("data-dog-transport",10,this.dispatchFunction)};var tt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===St){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_t(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 Lu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:ce(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),kt,Ht=class{static{s(this,"RemoteLogTransport")}constructor(e){kt||(kt=new T("remote-log-transport",1,Lu(e)))}async log(e,n){kt.enqueue(e),n.waitUntil(kt.waitUntilFlushed())}};var Su={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ko=s((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:Su[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var _u=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=Ko(n,r);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Ut,Nt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Ut||(Ut=new T("unified-log-transport",1,_u(e)))}async log(e,n){Ut.enqueue(e),n.waitUntil(Ut.waitUntilFlushed())}};var tr=(0,Wo.debug)("zuplo:logging"),Mt=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(b.instance),this.userCoreLogger=this.setupUserCoreLogger(b.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;tr("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(je);return o?r.push(new tt(o.logger,e.logFormat)):e.isDeno&&r.push(new Xe(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Nt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Je(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){tr("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(je);if(i&&i.captureUserLogs===!0?n.push(new tt(i.logger,e.logFormat)):e.isDeno&&n.push(new Xe(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Ht({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new Qe({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new et({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return Ee.forEach(a=>{a instanceof H&&n.push(a.getTransport())}),new Je(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){tr("Gateway.createRequestLoggers");let a=new vt(r,o,i),u=new Ke(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Ke(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var fe=class{static{s(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 nr=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Te=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},rr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ce=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof fe||e instanceof k))throw new S("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new nr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new rr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Te(i.config,i.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 Te(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Du=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],te=(0,Yo.debug)("zuplo:runtime"),ku=s(t=>{let e=t.findIndex(n=>n.name===Ge.name);return e>-1?[...t.splice(e),Ge]:[...t,Ge]},"setupSystemNoVersion"),V=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;te("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new Mt(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(te("Gateway.initialize"),!t.#e){await Ao(i);let a=new t(e,n,r,o);t.#e=a}return t.#e}static purgeGatewayCache(){te("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new S("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Ot,It,z];#o;setupRoutes=()=>{te("Gateway.setupRoutes");let e=this.routeData,n=ku(e.versions),r=new Ce(n);if(e.routes.length===0)return qn(r,this),zn(r,this),$n(r,this),So(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;return o&&(Mo(r,this),No(r,this)),qn(r,this),zn(r,this),$n(r,this),e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let u=a,c=new U(this.#r,u,this),l=new fe(i);r.addRoute(l,c.execute)}),_o(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 f("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((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 te("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){te("Gateway.internalErrorResponse");let o={};if(b.instance.isDeno){if(r instanceof E&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=q(r.cause);"stack"in i&&(i.stack=Go(i.stack)),o={cause:i}}}return I.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return no.forEach(r=>{n.delete(r)}),b.instance.isDeno&&ro.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(qe)??e.headers.get(Jr),o=e.headers.get(Pe);if(!r){r=crypto.randomUUID();let w=new Headers(e.headers);w.set(qe,r),e=new Request(e,{headers:w})}if(["GET","HEAD"].includes(e.method)&&e.body){let w=new Headers(e.headers);w.set(Kr,"true"),e=new Request(e,{headers:w,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new S(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Zt(e.headers),R=this.#s(e),m=new _(R,{params:d.params}),y=new qt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),P=Z.initialize(y,m);if(d.routeConfiguration===Bn&&ze.value?.notFoundHandler!==void 0){let w=this.#n.lookupByPathOnly(l);P.pathOnlyMatches=w.map(v=>v.routeConfiguration).filter(v=>v instanceof fe)}try{if(A.addLogger(y,u),!c.pathname.startsWith("/__zuplo")){let D=await vo(m,y);if(D instanceof Response)return D;{let L=Z.getContextExtensions(y);m=D,L.latestRequest=m}}[...Du,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(D=>new RegExp(D).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let v=d.executableHandler;Hu(v,d,e),te("Gateway.handleRequest - call user handler");let C=await v(m,y);if(te("Gateway.handleRequest - user handler"),!(C instanceof Response))throw new E(`Invalid Response type from the request handler: ${typeof C}`);if(C.bodyUsed)throw new E("The response object has already been used. Return a new response instead.");if(C.headers.get(qe)===null&&!C.webSocket){let D=new Headers(C.headers);return D.set(qe,r),new Response(C.body,{status:C.status,statusText:C.statusText,headers:D,cf:C.cf})}else return C}catch(w){return te("Gateway - error executing handler",w),w instanceof E?(a.error(w),u.warn(w)):u.error(w),await this.#i(m,y,w)}}};function Hu(t,e,n){if(te("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Hu,"checkHandler");var Qo=s(async(t,e,n)=>{let r=V.instance.routeData.policies,o=Ve([t],r);if(o.length===0)throw new E(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Zt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(xn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(On)??void 0}get city(){return this.#e.get(Rn)??this.#e.get(Wr)??void 0}get continent(){return this.#e.get(wn)??this.#e.get(Yr)??void 0}get country(){return this.#e.get(Pn)??this.#e.get(Qr)??void 0}get latitude(){return this.#e.get(In)??this.#e.get(eo)??void 0}get longitude(){return this.#e.get(En)??this.#e.get(Xr)??void 0}get colo(){return this.#e.get(vn)??void 0}get postalCode(){return this.#e.get(Tn)??void 0}get metroCode(){return this.#e.get(Cn)??void 0}get region(){return this.#e.get(An)??void 0}get regionCode(){return this.#e.get(Ln)??void 0}get timezone(){return this.#e.get(Sn)??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}}},Ie=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},xe=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},Z=class t{static{s(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 E(`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 i of this.#n)o=await i(e,n,r);return o}},qt=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Qo(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingFinalHook=u=>{Z.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var Ft=class t{static{s(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)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Uu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function or(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Uu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(or,"isRestrictedEnvVariableName");function ir(t){return!!t.startsWith("ZUPLO_")}s(ir,"isZuploReadableEnvVariableName");var nt=new Proxy({},{get(t,e){if(or(String(e))&&!ir(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var ei=Re(ge());var W=(0,ei.debug)("zuplo:runtime:external-service");function ti(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=b.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(ti,"getServiceAuth");async function ni(t){let e=ti();if(!e)throw W("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.");if(typeof t!="string")throw W("Cannot call external service with Request object"),new E("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 i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(b.instance.useSha256ServiceRouting){W("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await oi(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw W("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(ni,"externalServiceTunnelConfig");async function ri(t,e){let n=ti();if(n)if(W(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(b.instance.useSha256ServiceRouting){W("Using sha256 service routing");let d=b.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await oi(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw W("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);W(`Calling external service: ${c.toString()}`);let l=await Ae(c.toString(),i);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 E("Could not connect to secure tunnel.");return l}else throw W("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw W("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}s(ri,"externalServiceHandler");async function oi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Nu(r);W(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Xo(`${i}-${o}`),l=await Xo(`${i}-${a}-${u}`);return`${c}.${l}`}s(oi,"hashServiceName");async function Xo(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Xo,"hashSegment");function Nu(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Nu,"sanitizeEnvironmentType");var ii=new Map;ii.set("service:",ri);var Ae=globalThis.fetch;globalThis.fetch=function(t,e){let n=Mu(e);if(typeof t=="string"){let r=new URL(t),o=ii.get(r.protocol);return o?o(t,n):Ae(t,n)}else return Ae(t,n)};var Mu=s(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 si=s(()=>{V.purgeGatewayCache()},"purgeGatewayCache"),$t=class{constructor(e,n,r,o,i,a,u){this.routeData=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{b.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await V.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:"Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:b.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(i,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var fi=Re(ge());function Zu(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="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}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=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Zu,"lexer");function sr(t,e){e===void 0&&(e={});for(var n=Zu(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Fu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(J){if(c<n.length&&n[c].type===J)return n[c++].value},"tryConsume"),p=s(function(J){var K=d(J);if(K!==void 0)return K;var ye=n[c],be=ye.type,hn=ye.index;throw new TypeError("Unexpected ".concat(be," at ").concat(hn,", expected ").concat(J))},"mustConsume"),R=s(function(){for(var J="",K;K=d("CHAR")||d("ESCAPED_CHAR");)J+=K;return J},"consumeText");c<n.length;){var m=d("CHAR"),y=d("NAME"),P=d("PATTERN");if(y||P){var w=m||"";o.indexOf(w)===-1&&(l+=w,w=""),l&&(a.push(l),l=""),a.push({name:y||u++,prefix:w,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var v=m||d("ESCAPED_CHAR");if(v){l+=v;continue}l&&(a.push(l),l="");var C=d("OPEN");if(C){var w=R(),D=d("NAME")||"",L=d("PATTERN")||"",B=R();p("CLOSE"),a.push({name:D||(L?u++:""),pattern:D&&!L?i:L,prefix:w,suffix:B,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(sr,"parse");function ai(t,e){return qu(sr(t,e),e)}s(ai,"compile");function qu(t,e){e===void 0&&(e={});var n=$u(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,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 R=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<R.length;P++){var w=o(R[P],p);if(a&&!u[d].test(w))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(w,'"'));l+=p.prefix+w+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var w=o(String(R),p);if(a&&!u[d].test(w))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(w,'"'));l+=p.prefix+w+p.suffix;continue}if(!m){var v=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(v))}}return l}}s(qu,"tokensToFunction");function Fu(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Fu,"escapeString");function $u(t){return t&&t.sensitive?"":"i"}s($u,"flags");var di=Re(ge());var Bu=(0,di.debug)("zuplo:runtime"),ur=new TextEncoder,ui={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"},zu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Le=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,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=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new cr(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){Bu("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);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 f("An unknown error occurred, ensure retries is not negative")}},cr=class{static{s(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:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:R,appendSessionToken:m,allHeaders:y,singleEncode:P}){if(n==null)throw new TypeError("url is a required option");if(i==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=i,this.secretAccessKey=a,this.sessionToken=u;let w,v;(!c||!l)&&([w,v]=Gu(this.url,this.headers)),this.service=c||w||"",this.region=l||v||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>y||!zu.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
57
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!C.has("X-Amz-Expires")&&C.set("X-Amz-Expires","86400"),C.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),C.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),C.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=li(this.encodedPath);let D=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(D.has(L))return!1;D.add(L)}return!0}).map(L=>L.map(B=>li(encodeURIComponent(B)))).sort(([L,B],[J,K])=>L<J?-1:L>J?1:B<K?-1:B>K?1:0).map(L=>L.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 rt("AWS4"+this.secretAccessKey,e),i=await rt(o,this.region),a=await rt(i,this.service);r=await rt(a,"aws4_request"),this.cache.set(n,r)}return ar(await rt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ar(await ci(await this.canonicalString()))].join(`
54
+ `).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"||Ho(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 m="["+p.newline+a.map((y,P)=>{let w=a.length-1===P?p.newline:","+p.newlineOrSpace,v=i(y,u,c+d,l+1);return u.transform&&(v=u.transform(a,P,v)),p.indent+v+w}).join("")+p.pad+"]";return r.pop(),R(m)}if(je(a)){let m=Uo(a);if(u.filter&&(m=m.filter(P=>u.filter?.(a,P))),m.length===0)return"{}";r.push(a);let y="{"+p.newline+m.map((P,w)=>{let v=m.length-1===w?p.newline:","+p.newlineOrSpace,C=typeof P=="symbol",D=!C&&/^[a-z$_][$\w]*$/i.test(P),L=C||D?P:i(P,u,"",l+1),B=i(a[P],u,c+d,l+1);return u.transform&&(B=u.transform(a,P,B)),p.indent+String(L)+": "+B+v}).join("")+p.pad+"}";return r.pop(),R(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(Tt,"stringifyObject");function le(t){return t.map(e=>q(e))}s(le,"makeErrorsSerializable");function ve(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:re(q(e))}s(ve,"extractBestMessage");function Xo(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Je(n))if(n.stack)e.push(n.stack);else{let r=Tt(q(n));e.push(r)}else if(typeof n=="object"){let r=Tt(n);e.push(r)}else{let r=Xn(n);e.push(r)}}),e.join(`
56
+ `)}s(Xo,"messagesToMultilineText");function re(t){return typeof t=="string"?t:JSON.stringify(t)}s(re,"stringifyNonString");function Xn(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"?$n(t):"unknown"}s(Xn,"stringifyNonStringToText");var Ct=require("jose");async function Te(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Te,"fetchRetry");async function ee({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ct.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ee,"getTokenFromGcpServiceAccount");async function ei(t,e,n){return ti(t,{token:e,returnSecureToken:!0},n)}s(ei,"exchangeFirebaseJwtForIdToken");async function At(t,e,n){return ti(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(At,"exchangeGgpJwtForIdToken");async function ti(t,e,n){let r=await Te(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new E({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ti,"fetchToken");var z=class t{static{s(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(0,Ct.importPKCS8)(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 Lt=class extends H{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xe(this.options)}},Du="https://logging.googleapis.com/v2/entries:write?alt=json",er={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xe=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=b.instance.loggingEnvironmentType,this.#i=b.instance.loggingEnvironmentStage,this.#r=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:le(e.messages)};this.#t||(this.#t=await z.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:er[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&&(i.labels.rayId=e.rayId);let a=ve(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await z.init(this.#e));let n=await ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Du,{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 T("google-log-transport",1,this.dispatchFunction)};var St="gcp";function _t(t){let e={allMessages:le(t.messages)},n="zuplo-production",r=ve(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:er[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}s(_t,"gcpLogFormat");var et=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===St){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_t(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 Dt=class extends H{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new tt(this.options)}},tr="__ddtags",nr="__ddattr",rr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ku=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(rr(r)):n.push(`${rr(r)}:${rr(o.toString())}`)}),n.join(",")},"formatTags"),tt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[tr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[tr]!==void 0);a>-1&&(Object.assign(r,i[a][tr]),i.splice(a,1));let u={},c=n.custom[nr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[nr]!==void 0);l>-1&&(Object.assign(u,i[l][nr]),i.splice(l,1));let d=le(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:ve(d),service:e.loggingId,ddtags:ku(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),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 T("data-dog-transport",10,this.dispatchFunction)};var nt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===St){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_t(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 Hu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:le(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),kt,Ht=class{static{s(this,"RemoteLogTransport")}constructor(e){kt||(kt=new T("remote-log-transport",1,Hu(e)))}async log(e,n){kt.enqueue(e),n.waitUntil(kt.waitUntilFlushed())}};var Uu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ni=s((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:Uu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Nu=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=ni(n,r);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Ut,Nt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Ut||(Ut=new T("unified-log-transport",1,Nu(e)))}async log(e,n){Ut.enqueue(e),n.waitUntil(Ut.waitUntilFlushed())}};var or=(0,ri.debug)("zuplo:logging"),Mt=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(b.instance),this.userCoreLogger=this.setupUserCoreLogger(b.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;or("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(We);return o?r.push(new nt(o.logger,e.logFormat)):e.isDeno&&r.push(new et(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Nt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Ye(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){or("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(We);if(i&&i.captureUserLogs===!0?n.push(new nt(i.logger,e.logFormat)):e.isDeno&&n.push(new et(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Ht({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new Xe({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new tt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return Ie.forEach(a=>{a instanceof H&&n.push(a.getTransport())}),new Ye(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){or("Gateway.createRequestLoggers");let a=new vt(r,o,i),u=new Qe(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Qe(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ye=class{static{s(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 ir=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ce=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},sr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ae=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ye||e instanceof k))throw new S("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new ir(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new sr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Ce(i.config,i.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 Ce(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Mu=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],te=(0,oi.debug)("zuplo:runtime"),Zu=s(t=>{let e=t.findIndex(n=>n.name===Ge.name);return e>-1?[...t.splice(e),Ge]:[...t,Ge]},"setupSystemNoVersion"),G=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;te("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new Mt(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(te("Gateway.initialize"),!t.#e){await _o(i);let a={...e,corsPolicies:Fo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){te("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new S("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Ot,It,V];#o;setupRoutes=()=>{te("Gateway.setupRoutes");let e=this.routeData,n=Zu(e.versions),r=new Ae(n);if(e.routes.length===0)return qn(r,this),Kn(r,this),jn(r,this),$o(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;return o&&(Ko(r,this),Jo(r,this)),qn(r,this),Kn(r,this),jn(r,this),e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let u=a,c=new U(this.#r,u,this),l=new ye(i);r.addRoute(l,c.execute)}),Bo(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 f("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((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 te("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){te("Gateway.internalErrorResponse");let o={};if(b.instance.isDeno){if(r instanceof E&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=q(r.cause);"stack"in i&&(i.stack=Qo(i.stack)),o={cause:i}}}return I.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return io.forEach(r=>{n.delete(r)}),b.instance.isDeno&&so.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Fe)??e.headers.get(Yr),o=e.headers.get(Ee);if(!r){r=crypto.randomUUID();let w=new Headers(e.headers);w.set(Fe,r),e=new Request(e,{headers:w})}if(["GET","HEAD"].includes(e.method)&&e.body){let w=new Headers(e.headers);w.set(Qr,"true"),e=new Request(e,{headers:w,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new S(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Zt(e.headers),R=this.#s(e),m=new _(R,{params:d.params}),y=new qt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),P=Z.initialize(y,m);if(d.routeConfiguration===Jn&&ze.value?.notFoundHandler!==void 0){let w=this.#n.lookupByPathOnly(l);P.pathOnlyMatches=w.map(v=>v.routeConfiguration).filter(v=>v instanceof ye)}try{if(A.addLogger(y,u),!c.pathname.startsWith("/__zuplo")){let D=await Ao(m,y);if(D instanceof Response)return D;{let L=Z.getContextExtensions(y);m=D,L.latestRequest=m}}[...Mu,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(D=>new RegExp(D).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let v=d.executableHandler;qu(v,d,e),te("Gateway.handleRequest - call user handler");let C=await v(m,y);if(te("Gateway.handleRequest - user handler"),!(C instanceof Response))throw new E(`Invalid Response type from the request handler: ${typeof C}`);if(C.bodyUsed)throw new E("The response object has already been used. Return a new response instead.");if(C.headers.get(Fe)===null&&!C.webSocket){let D=new Headers(C.headers);return D.set(Fe,r),new Response(C.body,{status:C.status,statusText:C.statusText,headers:D,cf:C.cf})}else return C}catch(w){return te("Gateway - error executing handler",w),w instanceof E?(a.error(w),u.warn(w)):u.error(w),await this.#i(m,y,w)}}};function qu(t,e,n){if(te("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(qu,"checkHandler");var ii=s(async(t,e,n)=>{let r=G.instance.routeData.policies,o=Ke([t],r);if(o.length===0)throw new E(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Zt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(xn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(On)??void 0}get city(){return this.#e.get(Rn)??this.#e.get(Xr)??void 0}get continent(){return this.#e.get(wn)??this.#e.get(eo)??void 0}get country(){return this.#e.get(Pn)??this.#e.get(to)??void 0}get latitude(){return this.#e.get(In)??this.#e.get(ro)??void 0}get longitude(){return this.#e.get(En)??this.#e.get(no)??void 0}get colo(){return this.#e.get(vn)??void 0}get postalCode(){return this.#e.get(Tn)??void 0}get metroCode(){return this.#e.get(Cn)??void 0}get region(){return this.#e.get(An)??void 0}get regionCode(){return this.#e.get(Ln)??void 0}get timezone(){return this.#e.get(Sn)??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}}},xe=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Oe=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},Z=class t{static{s(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 E(`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 i of this.#n)o=await i(e,n,r);return o}},qt=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>ii(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingFinalHook=u=>{Z.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var Ft=class t{static{s(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)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Fu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ar(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Fu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(ar,"isRestrictedEnvVariableName");function ur(t){return!!t.startsWith("ZUPLO_")}s(ur,"isZuploReadableEnvVariableName");var rt=new Proxy({},{get(t,e){if(ar(String(e))&&!ur(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var ai=we(me());var W=(0,ai.debug)("zuplo:runtime:external-service");function ui(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=b.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(ui,"getServiceAuth");async function ci(t){let e=ui();if(!e)throw W("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.");if(typeof t!="string")throw W("Cannot call external service with Request object"),new E("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 i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(b.instance.useSha256ServiceRouting){W("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await di(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw W("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(ci,"externalServiceTunnelConfig");async function li(t,e){let n=ui();if(n)if(W(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(b.instance.useSha256ServiceRouting){W("Using sha256 service routing");let d=b.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await di(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw W("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);W(`Calling external service: ${c.toString()}`);let l=await Le(c.toString(),i);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 E("Could not connect to secure tunnel.");return l}else throw W("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw W("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}s(li,"externalServiceHandler");async function di(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=$u(r);W(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await si(`${i}-${o}`),l=await si(`${i}-${a}-${u}`);return`${c}.${l}`}s(di,"hashServiceName");async function si(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(si,"hashSegment");function $u(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s($u,"sanitizeEnvironmentType");var pi=new Map;pi.set("service:",li);var Le=globalThis.fetch;globalThis.fetch=function(t,e){let n=Bu(e);if(typeof t=="string"){let r=new URL(t),o=pi.get(r.protocol);return o?o(t,n):Le(t,n)}else return Le(t,n)};var Bu=s(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 gi=s(()=>{G.purgeGatewayCache()},"purgeGatewayCache"),$t=class{constructor(e,n,r,o,i,a,u){this.routeData=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{b.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await G.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof f&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:b.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var Ei=we(me());function Vu(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="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}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=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Vu,"lexer");function cr(t,e){e===void 0&&(e={});for(var n=Vu(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Gu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(J){if(c<n.length&&n[c].type===J)return n[c++].value},"tryConsume"),p=s(function(J){var K=d(J);if(K!==void 0)return K;var be=n[c],Re=be.type,hn=be.index;throw new TypeError("Unexpected ".concat(Re," at ").concat(hn,", expected ").concat(J))},"mustConsume"),R=s(function(){for(var J="",K;K=d("CHAR")||d("ESCAPED_CHAR");)J+=K;return J},"consumeText");c<n.length;){var m=d("CHAR"),y=d("NAME"),P=d("PATTERN");if(y||P){var w=m||"";o.indexOf(w)===-1&&(l+=w,w=""),l&&(a.push(l),l=""),a.push({name:y||u++,prefix:w,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var v=m||d("ESCAPED_CHAR");if(v){l+=v;continue}l&&(a.push(l),l="");var C=d("OPEN");if(C){var w=R(),D=d("NAME")||"",L=d("PATTERN")||"",B=R();p("CLOSE"),a.push({name:D||(L?u++:""),pattern:D&&!L?i:L,prefix:w,suffix:B,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(cr,"parse");function mi(t,e){return zu(cr(t,e),e)}s(mi,"compile");function zu(t,e){e===void 0&&(e={});var n=ju(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,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 R=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<R.length;P++){var w=o(R[P],p);if(a&&!u[d].test(w))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(w,'"'));l+=p.prefix+w+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var w=o(String(R),p);if(a&&!u[d].test(w))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(w,'"'));l+=p.prefix+w+p.suffix;continue}if(!m){var v=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(v))}}return l}}s(zu,"tokensToFunction");function Gu(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Gu,"escapeString");function ju(t){return t&&t.sensitive?"":"i"}s(ju,"flags");var bi=we(me());var Ju=(0,bi.debug)("zuplo:runtime"),dr=new TextEncoder,fi={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"},Ku=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Se=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,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=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new pr(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){Ju("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);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 f("An unknown error occurred, ensure retries is not negative")}},pr=class{static{s(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:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:R,appendSessionToken:m,allHeaders:y,singleEncode:P}){if(n==null)throw new TypeError("url is a required option");if(i==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=i,this.secretAccessKey=a,this.sessionToken=u;let w,v;(!c||!l)&&([w,v]=Wu(this.url,this.headers)),this.service=c||w||"",this.region=l||v||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>y||!Ku.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
57
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!C.has("X-Amz-Expires")&&C.set("X-Amz-Expires","86400"),C.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),C.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),C.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=yi(this.encodedPath);let D=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(D.has(L))return!1;D.add(L)}return!0}).map(L=>L.map(B=>yi(encodeURIComponent(B)))).sort(([L,B],[J,K])=>L<J?-1:L>J?1:B<K?-1:B>K?1:0).map(L=>L.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 ot("AWS4"+this.secretAccessKey,e),i=await ot(o,this.region),a=await ot(i,this.service);r=await ot(a,"aws4_request"),this.cache.set(n,r)}return lr(await ot(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,lr(await hi(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
- `)}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 E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=ar(await ci(this.body||""))}return e}};async function rt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?ur.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,ur.encode(e))}s(rt,"hmac");async function ci(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?ur.encode(t):t)}s(ci,"hash");function ar(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(ar,"buf2hex");function li(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(li,"encodeRfc3986");function Gu(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in ui?[ui[i],a]:[i,a]}s(Gu,"guessServiceRegion");function Vu(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}s(Vu,"b64ToUint6");function pi(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,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Vu(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(pi,"base64Decode");function Bt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Bt,"uint6ToB64");function gi(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Bt(o>>>18&63),Bt(o>>>12&63),Bt(o>>>6&63),Bt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(gi,"base64Encode");function Se(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Se,"numberToString");function ju(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Se(Math.floor(n/60)),i=Se(n%60);return`${r}${o}${i}`}s(ju,"getCLFOffset");function lr(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=Se(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Se(t.getHours()),a=Se(t.getMinutes()),u=Se(t.getSeconds()),c=ju(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(lr,"toCLFDate");var mi=(0,fi.debug)("zuplo:runtime"),Ju="X-Amzn-Trace-Id",Ku="x-amzn-errortype",hi=[],Wu=s(async(t,e,n)=>{let r=n;for await(let o of hi)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Ju)??void 0,this.errorType=n.get(Ku)??void 0}},yi={addSendingAwsLambdaEventHook:t=>{hi.push(t)}};async function bi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new Le({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(mi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,R]=await ec(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=Xu(t,e):y=await Qu(t,e,{useAwsResourcePathStyle:u}),mi("Calling onSendingAwsLambdaEvent hook");let P=await Wu(t,e,y);P.body=p,P.isBase64Encoded=R;let w=await l.fetch(d,{body:JSON.stringify(P)});try{return Yu(w)}catch(v){if(v instanceof j){let C=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&v.traceId?{AMZN_TRACE_ID_HEADER:v.traceId}:void 0;return I.internalServerError(t,e,void 0,C)}throw v}}s(bi,"awsLambdaHandler");async function Yu(t){let e;try{e=await t.json()}catch{throw new j("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 j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(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 j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`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 j(`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 j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=pi(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 j(`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})}s(Yu,"getResponse");async function Qu(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))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:i,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:lr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:nc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Qu,"buildEventVersion1");function Xu(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});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:lr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(Xu,"buildEventVersion2");async function ec(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&&tc(e,o)){let i=await t.arrayBuffer();n=gi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(ec,"getBodyResult");function tc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(tc,"matchesContentType");function nc(t,e=!1){if(!e)return t;let n=sr(t),r=ai(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(nc,"getResourcePath");var rc=[502,503,504];async function _e(t,e){if(rc.includes(t.status)){let n=A.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(_e,"logBadGatewayResponses");var dr;function le(t){if(dr===void 0){let n=b.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),dr=n}return t.log[dr]}s(le,"getHandlerUserLogFunction");async function Ri(t,e){let n=b.instance.build.BUILD_ID,{buildAssetsUrl:r}=b.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=oc(i);if(!a.isValid)throw new f(a.error);let u;b.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return I.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 _e(l,e),l}s(Ri,"openApiSpecHandler");var oc=s(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 wi(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(wi,"redirectHandler");function ic(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}`}s(ic,"join");async function Pi(t,e){let n=le(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 f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=ic(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}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),_e(p,e),p}s(Pi,"urlForwardHandler");var sc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Ei(t,e){let n=le(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("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?sc(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:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),_e(d,e),d}s(Ei,"urlRewriteHandler");async function Ii(t,e){let n=b.instance,r=e.route.handler.options,o=le(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("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 m=await ni(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let w in m.tunnelHeaders)p.set(w,m.tunnelHeaders[w])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{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(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}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})}s(Ii,"webSocketHandler");var pr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),xi=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];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 Oi(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{s(async u=>{let c=await xi(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Oi,"wireUpListeners");async function vi(t,e){let n=b.instance,r=e.route.handler.options,o=le(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("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 f("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 v=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${v}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),R.accept();let P=r.policies&&r.policies.inbound?pr(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?pr(r.policies.outbound,"outbound"):[];return Oi(R,y,t,e,P),Oi(y,R,t,e,w),new Response(null,{status:101,webSocket:p})}s(vi,"webSocketPipelineHandler");var zt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new gr(this.options)}},gr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(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 T("dyna-trace-log-transport",10,this.#i)};var Gt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new fr(this.options)}},mr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function ac(t,e){return btoa(`${t}:${e}`)}s(ac,"createBasicDigest");var fr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=ac(e.username,e.password),this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new mr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:re(q(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.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 T("loki-log-transport",10,this.#s)};var Vt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new hr(this.options)}},hr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(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(`
61
- `),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 T("sumo-logic-log-transport",10,this.#s)};var uc="d3a5b78f-8236-48f5-b1df-4fe269d41172",jt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new yr(this.options)}},yr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Vo(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{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.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=Wn(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${uc}`,{method:"POST",body:JSON.stringify(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 T("vmware-log-insights-log-transport",10,this.#s)};var Jt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new br(this.options)}},br=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("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:i}){this.awsClient=new Le({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=b.instance.loggingEnvironmentType,this.environment=b.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:re(q(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 Rr=new WeakMap,cc={tags:[]},Kt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new wr(this.options)}static setContext(n,r){let o=Rr.get(n);o||(o=cc);let i=Object.assign({...o},r);Rr.set(n,i)}},wr=class{static{s(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 T("data-dog-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Rr.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 i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}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 Pr(await r.text())}},Pr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Er=new WeakMap,lc={dimensions:[]},Wt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Ir(this.options)}static setContext(n,r){let o=Er.get(n);o||(o=lc);let i=Object.assign({...o},r);Er.set(n,i)}},Ir=class{static{s(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 T("dynatrace-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Er.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 i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new xr(await r.text())}},xr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(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 Qt=class extends Be{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Or(e,this.#e,this.#t)}},Ti=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),dc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Or=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...dc};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 T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Ti(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?Ti(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,i=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-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Ci=new Map;function Ai(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Ci.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ci.set(t,r),r}s(Ai,"statusCodesStringToNumberArray");function he(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new E(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(he,"getValueFromRequestUser");var Si=new WeakMap,Li={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Si.set(e,n)}};async function _i(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Ai(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Si.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(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)},R=Li[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),Li[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(_i,"AmberfloMeteringInboundPolicy");async function en(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("")}s(en,"sha256");var Di=new Map;async function F(t,e){let n,r=Di.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Di.set(t,n)),n}s(F,"getPolicyCacheName");var ki="key-metadata-cache-type";function pc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(pc,"getKeyValue");async function vr(t,e,n,r){if(!n.bucketName)if(nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=nt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=pc(a,o);if(!u||u==="")return i("No key present");let c=await gc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==ki&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await ve({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:ki,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(vr,"ApiKeyInboundPolicy");async function gc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(gc,"hashValue");var Hi=vr;var ot=require("jose");var Tr={},mc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Tr[e.jwkUrl]||(Tr[e.jwkUrl]=(0,ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ot.jwtVerify)(t,Tr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),fc=s(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 i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?mc:fc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),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 Ui=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ni=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("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 hc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function yc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"digestMessage");var bc=s(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 yc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.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=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Mi(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await bc(t,n),c=await i.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 R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);hc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Mi,"CachingInboundPolicy");var Zi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var qi=s(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 _(t,{headers:o})},"ClearHeadersInboundPolicy");var Fi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var $i=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Bi=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(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 zi=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=V.instance,i=Ve(n.policies,o?.routeData.policies);return Gn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Gi=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(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 Vi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))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 _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var De="__unknown__",ji=s(async(t,e,n,r)=>{let o={allow:{countries:He(n.allow?.countries,"allow.countries",r),regionCodes:He(n.allow?.regionCodes,"allow.regionCode",r),asns:He(n.allow?.asns,"allow.asOrganization",r)},block:{countries:He(n.block?.countries,"block.countries",r),regionCodes:He(n.block?.regionCodes,"block.regionCode",r),asns:He(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??De,a=e.incomingRequestProperties.regionCode?.toLowerCase()??De,u=e.incomingRequestProperties.asn?.toString()??De,c=o.ignoreUnknown&&i===De,l=o.ignoreUnknown&&a===De,d=o.ignoreUnknown&&u===De,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ke(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?ke(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ke(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ke,"blockedResponse");function He(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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(He,"toLowerStringArray");var Ji=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Wi=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Cr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Cr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),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 Ki(a[u])}else return a.length>0?Ki(a[0]):Cr(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 Ki(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})}}s(Ki,"generateResponse");var Cr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Rc="Incoming",wc={logRequestBody:!0,logResponseBody:!0};function Yi(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Yi,"headersToObject");function Qi(){return new Date().toISOString()}s(Qi,"timestamp");var Ar=new WeakMap,Pc={};function ts(t,e){let n=Ar.get(t);n||(n=Pc);let r=Object.assign({...n},e);Ar.set(t,r)}s(ts,"setMoesifContext");async function Xi(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(Xi,"readBody");var Ec={},Lr;function es(){if(!Lr)throw new E("Invalid State - no _lastLogger");return Lr}s(es,"getLastLogger");function Ic(t){let e=Ec[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);es().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||es().error({status:o.status,body:await o.text()})})),e}s(Ic,"getDispatcher");async function ns(t,e,n,r){Lr=e.log;let o=Qi(),i=Object.assign(wc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Xi(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Ic(i.applicationId),d=t.headers.get("true-client-ip"),p=Ar.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Yi(t.headers)},m=i.logResponseBody?await Xi(u,e):void 0,y={time:Qi(),status:u.status,headers:Yi(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Rc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(ns,"MoesifInboundPolicy");var rs=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var os=require("jose");var Sr,is=s(async(t,e,n,r)=>{if(!Sr)try{Sr=await(0,os.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:Sr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var as=Re(ge());var tn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},_r=class extends tn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Dr=class extends tn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function xc(t,e){if(Bo(t))throw new _r(e)}s(xc,"throwIfUndefinedOrNull");function it(t,e){if(xc(t,e),!We(t))throw new Dr(e,"string")}s(it,"throwIfNotString");var nn=class t{static{s(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 it(e,"redisClientUrl"),it(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}){it(e,"url");let i=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=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},rn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(it(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var on=(0,as.debug)("zuplo:policies:RateLimitInboundPolicy"),Oc="strict",vc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Tc=s(async t=>({key:`ip-${vc(t)}`}),"getIP"),Cc=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Ac=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),sn;function Lc(t,e){let n;if(sn)return sn;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new rn,sn=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!We(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!We(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=nn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return sn=n,n}s(Lc,"getRedisClient");async function ss(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ss,"getCountAndUpdateExpiry");function Sc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`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 f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Sc,"wrapUserFunction");var _c="Retry-After",kr=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[_c]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Sc(n,r),user:Cc,ip:Tc,all:Ac}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=Lc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Oc)==="async"){let L=await F(r,n),B=new oe(L,{logger:A.getLogger(e)}),J=ss(v,m,P,i,e.requestId),K=await B.get(v);if(K!==void 0&&K<=Date.now()){on(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let ye=Math.round((K-Date.now())/1e3);return u(y,ye)}return e.addEventListener("responseSending",ye=>{try{let be=ye,hn=be.mutableResponse;be.mutableResponse=(async()=>{let st=await J;if(st.count>R){let qs=Date.now()+st.ttlSeconds*1e3;return B.put(v,qs,st.ttlSeconds).catch(Br=>{throw i.error(Br),Br}),on(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,st.ttlSeconds)}return hn})()}catch(be){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,be)}}),t}let D=await ss(v,m,P,i,e.requestId);return D.count>R?(on(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;on(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Hr;function us(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(us,"headersToNameValuePairs");function Dc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Dc,"queryToNameValueParis");function kc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(kc,"parseIntOrUndefined");var cs={};async function ls(t,e,n,r){let o=new Date,i=Date.now();return Hr||(Hr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Hr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:us(t.headers),queryString:Dc(t.query)},response:{status:a.status,statusText:a.statusText,headers:us(a.headers),content:{size:kc(t.headers.get("content-length"))}}}]}}},d=cs[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),cs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ls,"ReadmeMetricsInboundPolicy");var ds=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var ps=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var gs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ms=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var fs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),hs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?fs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?fs():t},"RequestSizeLimitInboundPolicy");function ys(t,e,n){return`_${de(t+"_"+e+"_"+n)}`}s(ys,"getRawOperationDataIdentifierName");function an(t,e,n,r){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(an,"getIdForParameterSchema");function un(t,e,n){return`_${de(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${de(n.toLowerCase())}`}s(un,"getIdForRequestBodySchema");function bs(t,e){return`_${de(t)}__${de(e)}`}s(bs,"getIdForRefSchema");function de(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("")}s(de,"sanitizedIdentifierName");var Ue=s(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"),Ne=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=an(n,r,o,c.name),d=V.instance.schemaValidator[l],p=d(e[c.name]),R=Ur(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Ur=s(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 Rs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=un(t.route.path,e.method,o),u=V.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Ur(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Rs,"handleBodyValidation");function ws(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ue(t),i=Ne(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(ws,"handleHeadersValidation");function Ps(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Ps,"handlePathParameterValidation");function Es(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ue(t),o=Ne(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(Es,"handleQueryParameterValidation");var Nr=s(async(t,e,n)=>{let r=Es(e,t,n);if(r!==void 0||(r=Ps(e,t,n),r!==void 0)||(r=ws(e,t,n),r!==void 0))return r;let o=await Rs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Is=Nr;var xs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`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 i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Os=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var Ts=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`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 Cs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var As=s(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 Hc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ls=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Hc(n.sleepInMs),t},"SleepInboundPolicy");var Ss=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`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?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var _s=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await Uc(n,e);i.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 Uc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ve({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 i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("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 E("Response returned from Azure AD is not in the expected format.")}s(Uc,"getAccessToken");var Ds="https://accounts.google.com/o/oauth2/token",Mr,ks=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),Mr||(Mr=await G.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(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:Mr,audience:Ds,payload:o}),l=await At(Ds,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("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 Nc="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Mc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Zr,Hs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`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(Mc.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Zr||(Zr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:Zr,audience:Nc,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await jo(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var qr,Us=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),qr||(qr=await G.init(n.serviceAccountJson));let o=await ee({serviceAccount:qr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ns="https://www.googleapis.com/oauth2/v4/token",Fr,Ms=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Fr||(Fr=await G.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new we(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Fr,audience:Ns,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At(Ns,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Zs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.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 S("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 I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ht(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(ht,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`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 Zc={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"},Rt=Zc;var $r=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!$r.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${$r.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 mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new at("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("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)}};
60
+ `)}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 E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=lr(await hi(this.body||""))}return e}};async function ot(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?dr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,dr.encode(e))}s(ot,"hmac");async function hi(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?dr.encode(t):t)}s(hi,"hash");function lr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(lr,"buf2hex");function yi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(yi,"encodeRfc3986");function Wu(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in fi?[fi[i],a]:[i,a]}s(Wu,"guessServiceRegion");function Yu(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}s(Yu,"b64ToUint6");function Ri(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,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Yu(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Ri,"base64Decode");function Bt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Bt,"uint6ToB64");function wi(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Bt(o>>>18&63),Bt(o>>>12&63),Bt(o>>>6&63),Bt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(wi,"base64Encode");function _e(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(_e,"numberToString");function Qu(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=_e(Math.floor(n/60)),i=_e(n%60);return`${r}${o}${i}`}s(Qu,"getCLFOffset");function gr(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=_e(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=_e(t.getHours()),a=_e(t.getMinutes()),u=_e(t.getSeconds()),c=Qu(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(gr,"toCLFDate");var Pi=(0,Ei.debug)("zuplo:runtime"),Xu="X-Amzn-Trace-Id",ec="x-amzn-errortype",Ii=[],tc=s(async(t,e,n)=>{let r=n;for await(let o of Ii)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Xu)??void 0,this.errorType=n.get(ec)??void 0}},xi={addSendingAwsLambdaEventHook:t=>{Ii.push(t)}};async function Oi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new Se({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Pi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,R]=await ic(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=oc(t,e):y=await rc(t,e,{useAwsResourcePathStyle:u}),Pi("Calling onSendingAwsLambdaEvent hook");let P=await tc(t,e,y);P.body=p,P.isBase64Encoded=R;let w=await l.fetch(d,{body:JSON.stringify(P)});try{return nc(w)}catch(v){if(v instanceof j){let C=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&v.traceId?{AMZN_TRACE_ID_HEADER:v.traceId}:void 0;return I.internalServerError(t,e,void 0,C)}throw v}}s(Oi,"awsLambdaHandler");async function nc(t){let e;try{e=await t.json()}catch{throw new j("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 j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(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 j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`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 j(`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 j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=Ri(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 j(`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})}s(nc,"getResponse");async function rc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))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:i,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:gr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ac(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(rc,"buildEventVersion1");function oc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});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:gr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(oc,"buildEventVersion2");async function ic(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&&sc(e,o)){let i=await t.arrayBuffer();n=wi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(ic,"getBodyResult");function sc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(sc,"matchesContentType");function ac(t,e=!1){if(!e)return t;let n=cr(t),r=mi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(ac,"getResourcePath");var uc=[502,503,504];async function De(t,e){if(uc.includes(t.status)){let n=A.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(De,"logBadGatewayResponses");var mr;function de(t){if(mr===void 0){let n=b.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),mr=n}return t.log[mr]}s(de,"getHandlerUserLogFunction");async function vi(t,e){let n=b.instance.build.BUILD_ID,{buildAssetsUrl:r}=b.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=cc(i);if(!a.isValid)throw new f(a.error);let u;b.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return I.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 De(l,e),l}s(vi,"openApiSpecHandler");var cc=s(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 Ti(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Ti,"redirectHandler");function lc(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}`}s(lc,"join");async function Ci(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 f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=lc(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}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),De(p,e),p}s(Ci,"urlForwardHandler");var dc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Ai(t,e){let n=de(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("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?dc(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:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),De(d,e),d}s(Ai,"urlRewriteHandler");async function Li(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("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 m=await ci(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let w in m.tunnelHeaders)p.set(w,m.tunnelHeaders[w])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{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(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}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})}s(Li,"webSocketHandler");var fr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Si=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];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 _i(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{s(async u=>{let c=await Si(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(_i,"wireUpListeners");async function Di(t,e){let n=b.instance,r=e.route.handler.options,o=de(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return I.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("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 f("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 v=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${v}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),R.accept();let P=r.policies&&r.policies.inbound?fr(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?fr(r.policies.outbound,"outbound"):[];return _i(R,y,t,e,P),_i(y,R,t,e,w),new Response(null,{status:101,webSocket:p})}s(Di,"webSocketPipelineHandler");var Vt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new hr(this.options)}},hr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(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 T("dyna-trace-log-transport",10,this.#i)};var zt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new br(this.options)}},yr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function pc(t,e){return btoa(`${t}:${e}`)}s(pc,"createBasicDigest");var br=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=pc(e.username,e.password),this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new yr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:re(q(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.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 T("loki-log-transport",10,this.#s)};var Gt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:re(q(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(`
61
+ `),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 T("sumo-logic-log-transport",10,this.#s)};var gc="d3a5b78f-8236-48f5-b1df-4fe269d41172",jt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wr(this.options)}},wr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Xo(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{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.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=Xn(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${gc}`,{method:"POST",body:JSON.stringify(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 T("vmware-log-insights-log-transport",10,this.#s)};var Jt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Pr(this.options)}},Pr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("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:i}){this.awsClient=new Se({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=b.instance.loggingEnvironmentType,this.environment=b.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:re(q(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 Er=new WeakMap,mc={tags:[]},Kt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Ir(this.options)}static setContext(n,r){let o=Er.get(n);o||(o=mc);let i=Object.assign({...o},r);Er.set(n,i)}},Ir=class{static{s(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 T("data-dog-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Er.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 i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}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 xr(await r.text())}},xr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Or=new WeakMap,fc={dimensions:[]},Wt=class extends ue{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new vr(this.options)}static setContext(n,r){let o=Or.get(n);o||(o=fc);let i=Object.assign({...o},r);Or.set(n,i)}},vr=class{static{s(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 T("dynatrace-metrics-transport",10,this.dispatchFunction,A.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Or.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 i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Yt=class{static{s(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 Qt=class extends Ve{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Cr(e,this.#e,this.#t)}},ki=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),hc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Cr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...hc};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 T("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?ki(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?ki(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,i=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-i,c.user?.sub).catch(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Ui=new WeakMap,Hi={},Xt=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ui.set(e,n)}};async function Ni(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:qo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ui.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=he(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)},R=Hi[n.apiKey];if(!R){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async P=>{try{let w=n.url??"https://app.amberflo.io/ingest",v=await fetch(w,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":y}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(w){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${w.message}`),w}}),Hi[m]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Ni,"AmberfloMeteringInboundPolicy");async function en(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("")}s(en,"sha256");var Mi=new Map;async function F(t,e){let n,r=Mi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await en(JSON.stringify({policyName:t,options:e}))}`,Mi.set(t,n)),n}s(F,"getPolicyCacheName");var Zi="key-metadata-cache-type";function yc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(yc,"getKeyValue");async function Ar(t,e,n,r){if(!n.bucketName)if(rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=rt.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(w=>o.allowUnauthenticatedRequests?t:I.unauthorized(t,e,{detail:w}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=yc(a,o);if(!u||u==="")return i("No key present");let c=await bc(u),l=await F(r,o),d=new M(l,{logger:A.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Zi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},m=await Te({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.instance.systemUserAgent},body:JSON.stringify(R)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let w=await m.text(),v=JSON.parse(w);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),P={isValid:!0,typeId:Zi,user:{sub:y.name,data:y.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(Ar,"ApiKeyInboundPolicy");async function bc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(bc,"hashValue");var qi=Ar;var it=require("jose");var Lr={},Rc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Lr[e.jwkUrl]||(Lr[e.jwkUrl]=(0,it.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,it.jwtVerify)(t,Lr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),wc=s(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 i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,it.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),N=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>I.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Rc:wc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,m),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 Fi=s(async(t,e,n,r)=>N(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var $i=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>I.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let R=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(P=>P.username===R&&P.password===m);return y||await i("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 Pc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ec(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Ec,"digestMessage");var Ic=s(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 Ec(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.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=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Bi(t,e,n,r){let o=await F(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ic(t,n),c=await i.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 R=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Pc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Bi,"CachingInboundPolicy");var Vi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var zi=s(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 _(t,{headers:o})},"ClearHeadersInboundPolicy");var Gi=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var ji=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",N(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return N(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 Ki=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ke(n.policies,o?.routeData.policies);return Wn(i)(t,e)},"CompositeInboundPolicy");function $(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new f(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new f(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s($,"optionValidator");var Wi=s(async(t,e,n,r)=>($(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),N(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 Yi=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))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 _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ke="__unknown__",Qi=s(async(t,e,n,r)=>{let o={allow:{countries:Ue(n.allow?.countries,"allow.countries",r),regionCodes:Ue(n.allow?.regionCodes,"allow.regionCode",r),asns:Ue(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ue(n.block?.countries,"block.countries",r),regionCodes:Ue(n.block?.regionCodes,"block.regionCode",r),asns:Ue(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ke,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ke,u=e.incomingRequestProperties.asn?.toString()??ke,c=o.ignoreUnknown&&i===ke,l=o.ignoreUnknown&&a===ke,d=o.ignoreUnknown&&u===ke,p=o.allow.countries,R=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return He(t,e,r,i,a,u);let y=o.block.countries,P=o.block.regionCodes,w=o.block.asns;return y.length>0&&y.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||w.length>0&&w.includes(u)&&!d?He(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function He(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),I.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(He,"blockedResponse");function Ue(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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ue,"toLowerStringArray");var Xi=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ts=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Sr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Sr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),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 es(a[u])}else return a.length>0?es(a[0]):Sr(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 es(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})}}s(es,"generateResponse");var Sr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return I.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var xc="Incoming",Oc={logRequestBody:!0,logResponseBody:!0};function ns(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ns,"headersToObject");function rs(){return new Date().toISOString()}s(rs,"timestamp");var _r=new WeakMap,vc={};function ss(t,e){let n=_r.get(t);n||(n=vc);let r=Object.assign({...n},e);_r.set(t,r)}s(ss,"setMoesifContext");async function os(t,e){let n=t.headers.get("content-type"),r=t.clone();if(n&&n.indexOf("json")!==0)try{return await r.json()}catch(i){e.log.error(i)}let o=await r.text();return e.log.debug({textBody:o}),o}s(os,"readBody");var Tc={},Dr;function is(){if(!Dr)throw new E("Invalid State - no _lastLogger");return Dr}s(is,"getLastLogger");function Cc(t){let e=Tc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);is().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||is().error({status:o.status,body:await o.text()})})),e}s(Cc,"getDispatcher");async function as(t,e,n,r){Dr=e.log;let o=rs(),i=Object.assign(Oc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await os(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Cc(i.applicationId),d=t.headers.get("true-client-ip"),p=_r.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ns(t.headers)},m=i.logResponseBody?await os(u,e):void 0,y={time:rs(),status:u.status,headers:ns(u.headers),body:m},P={request:R,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:xc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(as,"MoesifInboundPolicy");var us=s(async(t,e,n,r)=>N(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var cs=require("jose");var kr,ls=s(async(t,e,n,r)=>{if(!kr)try{kr=await(0,cs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return N(t,e,{issuer:n.authUrl,secret:kr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ps=we(me());var tn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Hr=class extends tn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ur=class extends tn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Ac(t,e){if(Mo(t))throw new Hr(e)}s(Ac,"throwIfUndefinedOrNull");function st(t,e){if(Ac(t,e),!ce(t))throw new Ur(e,"string")}s(st,"throwIfNotString");var nn=class t{static{s(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 st(e,"redisClientUrl"),st(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}){st(e,"url");let i=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=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new S("Redis client failed with 401: Unauthorized"):new S(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},rn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(st(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new S("The in-memory redis client only supports /rate-limit calls")}};var on=(0,ps.debug)("zuplo:policies:RateLimitInboundPolicy"),Lc="strict",Sc=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),_c=s(async t=>({key:`ip-${Sc(t)}`}),"getIP"),Dc=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),kc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),sn;function Hc(t,e){let n;if(sn)return sn;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new rn,sn=n,n;let{authApiJWT:r,redisURL:o}=b.instance;if(!ce(o))throw new S(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new S(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=nn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!n||!n.isEnabled())throw new S(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return sn=n,n}s(Hc,"getRedisClient");async function ds(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ds,"getCountAndUpdateExpiry");function Uc(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`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 f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(Uc,"wrapUserFunction");var Nc="Retry-After",Nr=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new S(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Nc]=l.toString()),I.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Uc(n,r),user:Dc,ip:_c,all:kc}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",P=Hc(r,i),v=`bucket/${b.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Lc)==="async"){let L=await F(r,n),B=new oe(L,{logger:A.getLogger(e)}),J=ds(v,m,P,i,e.requestId),K=await B.get(v);if(K!==void 0&&K<=Date.now()){on(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let be=Math.round((K-Date.now())/1e3);return u(y,be)}return e.addEventListener("responseSending",be=>{try{let Re=be,hn=Re.mutableResponse;Re.mutableResponse=(async()=>{let at=await J;if(at.count>R){let zs=Date.now()+at.ttlSeconds*1e3;return B.put(v,zs,at.ttlSeconds).catch(Gr=>{throw i.error(Gr),Gr}),on(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(y,at.ttlSeconds)}return hn})()}catch(Re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Re)}}),t}let D=await ds(v,m,P,i,e.requestId);return D.count>R?(on(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(y,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;on(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Mr;function gs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(gs,"headersToNameValuePairs");function Mc(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Mc,"queryToNameValueParis");function Zc(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Zc,"parseIntOrUndefined");var ms={};async function fs(t,e,n,r){let o=new Date,i=Date.now();return Mr||(Mr={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?he(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?he(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:b.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Mr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:gs(t.headers),queryString:Mc(t.query)},response:{status:a.status,statusText:a.statusText,headers:gs(a.headers),content:{size:Zc(t.headers.get("content-length"))}}}]}}},d=ms[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),ms[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(fs,"ReadmeMetricsInboundPolicy");var hs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new _(t,{headers:i})},"RemoveHeadersInboundPolicy");var ys=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var bs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Rs=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ws=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ps=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ws():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ws():t},"RequestSizeLimitInboundPolicy");function Es(t,e,n){return`_${pe(t+"_"+e+"_"+n)}`}s(Es,"getRawOperationDataIdentifierName");function an(t,e,n,r){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(an,"getIdForParameterSchema");function un(t,e,n){return`_${pe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${pe(n.toLowerCase())}`}s(un,"getIdForRequestBodySchema");function Is(t,e){return`_${pe(t)}__${pe(e)}`}s(Is,"getIdForRefSchema");function pe(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("")}s(pe,"sanitizedIdentifierName");var Ne=s(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"),Me=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=an(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=Zr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Zr=s(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 xs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=I.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${m}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",y,[r],m),X(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=un(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=I.badRequest(e,t,{detail:m});return Q(n.validateBody)&&Y(t,n.logLevel??"info",m,[r],[m]),X(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Zr(l),R=I.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(xs,"handleBodyValidation");function Os(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ne(t),i=Me(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=I.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(Os,"handleHeadersValidation");function vs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(vs,"handlePathParameterValidation");function Ts(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ne(t),o=Me(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=I.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(Ts,"handleQueryParameterValidation");var qr=s(async(t,e,n)=>{let r=Ts(e,t,n);if(r!==void 0||(r=vs(e,t,n),r!==void 0)||(r=Os(e,t,n),r!==void 0))return r;let o=await xs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Cs=qr;var As=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`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 i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return I.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Ls=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Ss=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new _(t,{headers:i})},"SetHeadersInboundPolicy");var _s=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`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 Ds=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new _(i.toString(),t)},"SetQueryParamsInboundPolicy");var ks=s(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 qc=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Hs=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await qc(n.sleepInMs),t},"SleepInboundPolicy");var Us=s(async(t,e,n,r)=>{$(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await N(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof _))throw new S("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`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?I.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ns=s(async(t,e,n,r)=>{$(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await F(r,n),i=new M(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await Fc(n,e);i.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 Fc(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Te({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 i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("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 E("Response returned from Azure AD is not in the expected format.")}s(Fc,"getAccessToken");var Ms="https://accounts.google.com/o/oauth2/token",Fr,Zs=s(async(t,e,n,r)=>{$(n,r).required("serviceAccountJson","string"),Fr||(Fr=await z.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(" ")},i=await F(r,n),a=new M(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await ee({serviceAccount:Fr,audience:Ms,payload:o}),l=await At(Ms,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("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 $c="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Bc=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],$r,qs=s(async(t,e,n,r)=>{if($(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`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(Bc.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}$r||($r=await z.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=he(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await F(r,n),u=new M(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await en(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ee({serviceAccount:$r,audience:$c,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await ei(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Br,Fs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string"),Br||(Br=await z.init(n.serviceAccountJson));let o=await ee({serviceAccount:Br,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var $s="https://www.googleapis.com/oauth2/v4/token",Vr,Bs=s(async(t,e,n,r)=>{$(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vr||(Vr=await z.init(n.serviceAccountJson));let o=await F(r,n),i;n.useMemoryCacheOnly?i=new Pe(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ee({serviceAccount:Vr,audience:$s,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await At($s,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Vs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return I.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 S("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 I.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ln={Json:"application/json",Form:"application/x-www-form-urlencoded"};function yt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ln.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ln.Json)||!e?JSON.stringify(t):t}s(yt,"serialize");var dn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new S(`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 Vc={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"},wt=Vc;var zr=["sha-1","sha-256","sha-384","sha-512"],pn=class{static{s(this,"BaseCryptoBeta")}};var gn=class extends pn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!zr.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${zr.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 mn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var fn=class extends mn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ut("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("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)}};
63
63
  /*! For license information please see index.minified.js.LEGAL.txt */
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var s=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var a=(t,e)=>s(t,"name",{value:e,configurable:!0});var h=(t,e)=>{for(var r in e)s(t,r,{get:e[r],enumerable:!0})},u=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of m(e))!C.call(t,n)&&n!==r&&s(t,n,{get:()=>e[n],enumerable:!(o=l(e,n))||o.enumerable});return t};var x=t=>u(s({},"__esModule",{value:!0}),t);var I={};h(I,{VALID_COMPATIBILITY_DATES:()=>p,getIdForParameterSchema:()=>d,getIdForRefSchema:()=>f,getIdForRequestBodySchema:()=>c,getRawOperationDataIdentifierName:()=>g,sanitizedIdentifierName:()=>i});module.exports=x(I);var p=Object.freeze(["2023-03-14"]);function g(t,e,r){return`_${i(t+"_"+e+"_"+r)}`}a(g,"getRawOperationDataIdentifierName");function d(t,e,r,o){return`_${i(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${o.toLowerCase()}`}a(d,"getIdForParameterSchema");function c(t,e,r){return`_${i(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${i(r.toLowerCase())}`}a(c,"getIdForRequestBodySchema");function f(t,e){return`_${i(t)}__${i(e)}`}a(f,"getIdForRefSchema");function i(t){let e=[];for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);o>="0".charCodeAt(0)&&o<="9".charCodeAt(0)||o>="A".charCodeAt(0)&&o<="Z".charCodeAt(0)||o>="a".charCodeAt(0)&&o<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}a(i,"sanitizedIdentifierName");
25
+ "use strict";var s=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var a=(t,e)=>s(t,"name",{value:e,configurable:!0});var u=(t,e)=>{for(var r in e)s(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of m(e))!C.call(t,n)&&n!==r&&s(t,n,{get:()=>e[n],enumerable:!(o=l(e,n))||o.enumerable});return t};var x=t=>h(s({},"__esModule",{value:!0}),t);var P={};u(P,{VALID_COMPATIBILITY_DATES:()=>p,getIdForParameterSchema:()=>d,getIdForRefSchema:()=>f,getIdForRequestBodySchema:()=>g,getRawOperationDataIdentifierName:()=>c,sanitizedIdentifierName:()=>i});module.exports=x(P);var p=Object.freeze(["2023-03-14"]);function c(t,e,r){return`_${i(t+"_"+e+"_"+r)}`}a(c,"getRawOperationDataIdentifierName");function d(t,e,r,o){return`_${i(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${o.toLowerCase()}`}a(d,"getIdForParameterSchema");function g(t,e,r){return`_${i(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${i(r.toLowerCase())}`}a(g,"getIdForRequestBodySchema");function f(t,e){return`_${i(t)}__${i(e)}`}a(f,"getIdForRefSchema");function i(t){let e=[];for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);o>="0".charCodeAt(0)&&o<="9".charCodeAt(0)||o>="A".charCodeAt(0)&&o<="Z".charCodeAt(0)||o>="a".charCodeAt(0)&&o<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}a(i,"sanitizedIdentifierName");
26
26
  /*! For license information please see internal.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1563.0",
3
+ "version": "5.1565.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {