@zuplo/runtime 5.1811.0 → 5.1812.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.minified.js +7 -7
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var Ba=Object.create;var at=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var za=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var s=(t,e)=>at(t,"name",{value:e,configurable:!0});var Fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wa=(t,e)=>{for(var n in e)at(t,n,{get:e[n],enumerable:!0})},ko=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of za(e))!Ga.call(t,o)&&o!==n&&at(t,o,{get:()=>e[o],enumerable:!(r=ja(e,o))||r.enumerable});return t};var _e=(t,e,n)=>(n=t!=null?Ba(Va(t)):{},ko(e||!t||!t.__esModule?at(n,"default",{value:t,enumerable:!0}):n,t)),
|
|
25
|
+
"use strict";var Ba=Object.create;var at=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var za=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var s=(t,e)=>at(t,"name",{value:e,configurable:!0});var Fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wa=(t,e)=>{for(var n in e)at(t,n,{get:e[n],enumerable:!0})},ko=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of za(e))!Ga.call(t,o)&&o!==n&&at(t,o,{get:()=>e[o],enumerable:!(r=ja(e,o))||r.enumerable});return t};var _e=(t,e,n)=>(n=t!=null?Ba(Va(t)):{},ko(e||!t||!t.__esModule?at(n,"default",{value:t,enumerable:!0}):n,t)),Ja=t=>ko(at({},"__esModule",{value:!0}),t);var ei=Fe(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.generateColor=x.colorFunctions=x.stripColor=x.bgRgb24=x.rgb24=x.bgRgb8=x.rgb8=x.bgBrightWhite=x.bgBrightCyan=x.bgBrightMagenta=x.bgBrightBlue=x.bgBrightYellow=x.bgBrightGreen=x.bgBrightRed=x.bgBrightBlack=x.bgWhite=x.bgCyan=x.bgMagenta=x.bgBlue=x.bgYellow=x.bgGreen=x.bgRed=x.bgBlack=x.brightWhite=x.brightCyan=x.brightMagenta=x.brightBlue=x.brightYellow=x.brightGreen=x.brightRed=x.brightBlack=x.gray=x.white=x.cyan=x.magenta=x.blue=x.yellow=x.green=x.red=x.black=x.strikethrough=x.hidden=x.inverse=x.underline=x.italic=x.dim=x.bold=x.reset=x.getColorEnabled=x.setColorEnabled=void 0;var Vo=!0,ar=!Vo;function Ka(t){Vo||(ar=t)}s(Ka,"setColorEnabled");x.setColorEnabled=Ka;function Ya(){return ar}s(Ya,"getColorEnabled");x.getColorEnabled=Ya;function U(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(U,"code");function H(t,e){return ar?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(H,"run");function Qa(t){return H(t,U([0],0))}s(Qa,"reset");x.reset=Qa;function Xa(t){return H(t,U([1],22))}s(Xa,"bold");x.bold=Xa;function eu(t){return H(t,U([2],22))}s(eu,"dim");x.dim=eu;function tu(t){return H(t,U([3],23))}s(tu,"italic");x.italic=tu;function nu(t){return H(t,U([4],24))}s(nu,"underline");x.underline=nu;function ru(t){return H(t,U([7],27))}s(ru,"inverse");x.inverse=ru;function ou(t){return H(t,U([8],28))}s(ou,"hidden");x.hidden=ou;function iu(t){return H(t,U([9],29))}s(iu,"strikethrough");x.strikethrough=iu;function su(t){return H(t,U([30],39))}s(su,"black");x.black=su;function Go(t){return H(t,U([31],39))}s(Go,"red");x.red=Go;function Wo(t){return H(t,U([32],39))}s(Wo,"green");x.green=Wo;function Jo(t){return H(t,U([33],39))}s(Jo,"yellow");x.yellow=Jo;function Ko(t){return H(t,U([34],39))}s(Ko,"blue");x.blue=Ko;function Yo(t){return H(t,U([35],39))}s(Yo,"magenta");x.magenta=Yo;function Qo(t){return H(t,U([36],39))}s(Qo,"cyan");x.cyan=Qo;function au(t){return H(t,U([37],39))}s(au,"white");x.white=au;function uu(t){return Xo(t)}s(uu,"gray");x.gray=uu;function Xo(t){return H(t,U([90],39))}s(Xo,"brightBlack");x.brightBlack=Xo;function cu(t){return H(t,U([91],39))}s(cu,"brightRed");x.brightRed=cu;function lu(t){return H(t,U([92],39))}s(lu,"brightGreen");x.brightGreen=lu;function du(t){return H(t,U([93],39))}s(du,"brightYellow");x.brightYellow=du;function pu(t){return H(t,U([94],39))}s(pu,"brightBlue");x.brightBlue=pu;function mu(t){return H(t,U([95],39))}s(mu,"brightMagenta");x.brightMagenta=mu;function gu(t){return H(t,U([96],39))}s(gu,"brightCyan");x.brightCyan=gu;function fu(t){return H(t,U([97],39))}s(fu,"brightWhite");x.brightWhite=fu;function hu(t){return H(t,U([40],49))}s(hu,"bgBlack");x.bgBlack=hu;function yu(t){return H(t,U([41],49))}s(yu,"bgRed");x.bgRed=yu;function bu(t){return H(t,U([42],49))}s(bu,"bgGreen");x.bgGreen=bu;function wu(t){return H(t,U([43],49))}s(wu,"bgYellow");x.bgYellow=wu;function Ru(t){return H(t,U([44],49))}s(Ru,"bgBlue");x.bgBlue=Ru;function Pu(t){return H(t,U([45],49))}s(Pu,"bgMagenta");x.bgMagenta=Pu;function Eu(t){return H(t,U([46],49))}s(Eu,"bgCyan");x.bgCyan=Eu;function Iu(t){return H(t,U([47],49))}s(Iu,"bgWhite");x.bgWhite=Iu;function xu(t){return H(t,U([100],49))}s(xu,"bgBrightBlack");x.bgBrightBlack=xu;function vu(t){return H(t,U([101],49))}s(vu,"bgBrightRed");x.bgBrightRed=vu;function Tu(t){return H(t,U([102],49))}s(Tu,"bgBrightGreen");x.bgBrightGreen=Tu;function Su(t){return H(t,U([103],49))}s(Su,"bgBrightYellow");x.bgBrightYellow=Su;function Ou(t){return H(t,U([104],49))}s(Ou,"bgBrightBlue");x.bgBrightBlue=Ou;function Cu(t){return H(t,U([105],49))}s(Cu,"bgBrightMagenta");x.bgBrightMagenta=Cu;function Au(t){return H(t,U([106],49))}s(Au,"bgBrightCyan");x.bgBrightCyan=Au;function Lu(t){return H(t,U([107],49))}s(Lu,"bgBrightWhite");x.bgBrightWhite=Lu;function Ie(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(Ie,"clampAndTruncate");function _u(t,e){return H(t,U([38,5,Ie(e)],39))}s(_u,"rgb8");x.rgb8=_u;function ku(t,e){return H(t,U([48,5,Ie(e)],49))}s(ku,"bgRgb8");x.bgRgb8=ku;function Du(t,e){return typeof e=="number"?H(t,U([38,2,e>>16&255,e>>8&255,e&255],39)):H(t,U([38,2,Ie(e.r),Ie(e.g),Ie(e.b)],39))}s(Du,"rgb24");x.rgb24=Du;function Nu(t,e){return typeof e=="number"?H(t,U([48,2,e>>16&255,e>>8&255,e&255],49)):H(t,U([48,2,Ie(e.r),Ie(e.g),Ie(e.b)],49))}s(Nu,"bgRgb24");x.bgRgb24=Nu;var Mu=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 Uu(t){return t.replace(Mu,"")}s(Uu,"stripColor");x.stripColor=Uu;x.colorFunctions=[Go,Wo,Jo,Ko,Yo,Qo];function Hu(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(Hu,"hashCode");function Zu(t){let e=Math.abs(Hu(t));return x.colorFunctions[e%x.colorFunctions.length]}s(Zu,"generateColor");x.generateColor=Zu});var ti=Fe(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.format=void 0;function qu(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
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(qu,"format");_t.format=qu});var ai=Fe(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.inspect=void 0;function ke(t,e,n,r){let o={seen:[],stylize:$u,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Bu),kt(o,t,o.depth)}s(ke,"inspect");Dt.inspect=ke;ke.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]};ke.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function $u(t,e){return t}s($u,"stylizeNoColor");function Fu(t){return typeof t=="boolean"}s(Fu,"isBoolean");function ri(t){return t===void 0}s(ri,"isUndefined");function Bu(t,e){let n=ke.styles[e];return n?"\x1B["+ke.colors[n][0]+"m"+t+"\x1B["+ke.colors[n][1]+"m":t}s(Bu,"stylizeWithColor");function ur(t){return typeof t=="function"}s(ur,"isFunction");function oi(t){return typeof t=="string"}s(oi,"isString");function ju(t){return typeof t=="number"}s(ju,"isNumber");function ii(t){return t===null}s(ii,"isNull");function si(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(si,"hasOwn");function cr(t){return mr(t)&&gr(t)==="[object RegExp]"}s(cr,"isRegExp");function mr(t){return typeof t=="object"&&t!==null}s(mr,"isObject");function lr(t){return mr(t)&&(gr(t)==="[object Error]"||t instanceof Error)}s(lr,"isError");function ni(t){return mr(t)&&gr(t)==="[object Date]"}s(ni,"isDate");function gr(t){return Object.prototype.toString.call(t)}s(gr,"objectToString");function zu(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(zu,"arrayToHash");function Vu(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)si(e,String(a))?i.push(pr(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(pr(t,e,n,r,a,!0))}),i}s(Vu,"formatArray");function dr(t){return"["+Error.prototype.toString.call(t)+"]"}s(dr,"formatError");function kt(t,e,n){if(t.customInspect&&e&&ur(e.inspect)&&e.inspect!==ke&&!(e.constructor&&e.constructor.prototype===e)){let p=e.inspect(n,t);return oi(p)||(p=kt(t,p,n)),p}let r=Gu(t,e);if(r)return r;let o=Object.keys(e),i=zu(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(lr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return dr(e);if(o.length===0){if(ur(e)){let p=e.name?": "+e.name:"";return t.stylize("[Function"+p+"]","special")}if(cr(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(ni(e))return t.stylize(Date.prototype.toString.call(e),"date");if(lr(e))return dr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),ur(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),cr(e)&&(a=" "+RegExp.prototype.toString.call(e)),ni(e)&&(a=" "+Date.prototype.toUTCString.call(e)),lr(e)&&(a=" "+dr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return cr(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Vu(t,e,n,i,o):l=o.map(function(p){return pr(t,e,n,i,p,u)}),t.seen.pop(),Wu(l,a,c)}s(kt,"formatValue");function pr(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")),si(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(ii(n)?u=kt(t,c.value,null):u=kt(t,c.value,n-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(i?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
@@ -32,10 +32,10 @@
|
|
|
32
32
|
`))):u=t.stylize("[Circular]","special")),ri(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(pr,"formatProperty");function Gu(t,e){if(ri(e))return t.stylize("undefined","undefined");if(oi(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(ju(e))return t.stylize(""+e,"number");if(Fu(e))return t.stylize(""+e,"boolean");if(ii(e))return t.stylize("null","null")}s(Gu,"formatPrimitive");function Wu(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(Wu,"reduceToSingleString")});var ui=Fe(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.format=void 0;var
|
|
35
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(Wu,"reduceToSingleString")});var ui=Fe(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.format=void 0;var Ju=ti(),Ku=ai(),Yu=s((t,...e)=>(0,Ju.format)(Ku.inspect,t,e),"format");Nt.format=Yu});var De=Fe(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.debug=xe.withoutEnv=xe.Debugger=void 0;var Qu=ei(),Xu=ui(),Mt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Qu.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,Xu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};xe.Debugger=Mt;var Ut=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ci(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(ci,"extract");var lt;function ec(t){t||(t=[]),typeof t=="string"&&(t=ci(t)),lt=new Ut(t)}s(ec,"withoutEnv");xe.withoutEnv=ec;function tc(t){let e=globalThis.DEBUG;lt||(lt=new Ut(ci(e)));let n=new Mt(lt,t);return lt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(tc,"debug");xe.debug=tc});var qa=Fe((Sv,Za)=>{"use strict";var ed=Object.defineProperty,M=s((t,e)=>ed(t,"name",{value:e,configurable:!0}),"u"),Le=s((t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),"E"),td=Le(t=>{var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,i){return r}},n=M(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}),Ao=Le(t=>{"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",o=new RegExp("^"+r+"$"),i=M(function(u,c){let l=[],p=c.exec(u);for(;p;){let d=[];d.startIndex=c.lastIndex-p[0].length;let m=p.length;for(let g=0;g<m;g++)d.push(p[g]);l.push(d),p=c.exec(u)}return l},"getAllMatches"),a=M(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let p=Object.keys(c),d=p.length;for(let m=0;m<d;m++)l==="strict"?u[p[m]]=[c[p[m]]]:u[p[m]]=c[p[m]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=i,t.nameRegexp=r}),nd=Le((t,e)=>{"use strict";var n=class{static{s(this,"P")}static{M(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=n}),rd=Le((t,e)=>{var n=Ao();function r(d,m){let g={};if(d[m+3]==="O"&&d[m+4]==="C"&&d[m+5]==="T"&&d[m+6]==="Y"&&d[m+7]==="P"&&d[m+8]==="E"){m=m+9;let I=1,R=!1,v=!1,k="";for(;m<d.length;m++)if(d[m]==="<"&&!v){if(R&&a(d,m))m+=7,[entityName,val,m]=o(d,m+1),val.indexOf("&")===-1&&(g[p(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(R&&u(d,m))m+=8;else if(R&&c(d,m))m+=8;else if(R&&l(d,m))m+=9;else if(i)v=!0;else throw new Error("Invalid DOCTYPE");I++,k=""}else if(d[m]===">"){if(v?d[m-1]==="-"&&d[m-2]==="-"&&(v=!1,I--):I--,I===0)break}else d[m]==="["?R=!0:k+=d[m];if(I!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:g,i:m}}s(r,"ue"),M(r,"readDocType");function o(d,m){let g="";for(;m<d.length&&d[m]!=="'"&&d[m]!=='"';m++)g+=d[m];if(g=g.trim(),g.indexOf(" ")!==-1)throw new Error("External entites are not supported");let I=d[m++],R="";for(;m<d.length&&d[m]!==I;m++)R+=d[m];return[g,R,m]}s(o,"le"),M(o,"readEntityExp");function i(d,m){return d[m+1]==="!"&&d[m+2]==="-"&&d[m+3]==="-"}s(i,"ce"),M(i,"isComment");function a(d,m){return d[m+1]==="!"&&d[m+2]==="E"&&d[m+3]==="N"&&d[m+4]==="T"&&d[m+5]==="I"&&d[m+6]==="T"&&d[m+7]==="Y"}s(a,"de"),M(a,"isEntity");function u(d,m){return d[m+1]==="!"&&d[m+2]==="E"&&d[m+3]==="L"&&d[m+4]==="E"&&d[m+5]==="M"&&d[m+6]==="E"&&d[m+7]==="N"&&d[m+8]==="T"}s(u,"ge"),M(u,"isElement");function c(d,m){return d[m+1]==="!"&&d[m+2]==="A"&&d[m+3]==="T"&&d[m+4]==="T"&&d[m+5]==="L"&&d[m+6]==="I"&&d[m+7]==="S"&&d[m+8]==="T"}s(c,"ae"),M(c,"isAttlist");function l(d,m){return d[m+1]==="!"&&d[m+2]==="N"&&d[m+3]==="O"&&d[m+4]==="T"&&d[m+5]==="A"&&d[m+6]==="T"&&d[m+7]==="I"&&d[m+8]==="O"&&d[m+9]==="N"}s(l,"he"),M(l,"isNotation");function p(d){if(n.isName(d))return d;throw new Error(`Invalid entity name ${d}`)}s(p,"pe"),M(p,"validateEntityName"),e.exports=r}),od=Le((t,e)=>{var n=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function i(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&n.test(l))return Number.parseInt(l,16);{let p=r.exec(l);if(p){let d=p[1],m=p[2],g=a(p[3]),I=p[4]||p[6];if(!c.leadingZeros&&m.length>0&&d&&l[2]!=="."||!c.leadingZeros&&m.length>0&&!d&&l[1]!==".")return u;{let R=Number(l),v=""+R;return v.search(/[eE]/)!==-1||I?c.eNotation?R:u:l.indexOf(".")!==-1?v==="0"&&g===""||v===g||d&&v==="-"+g?R:u:m?g===v||d+g===v?R:u:l===v||l===d+v?R:u}}else return u}}s(i,"Te"),M(i,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}s(a,"ye"),M(a,"trimZeros"),e.exports=i}),id=Le((t,e)=>{"use strict";var n=Ao(),r=nd(),o=rd(),i=od(),a=class{static{s(this,"C")}static{M(this,"OrderedObjParser")}constructor(y){this.options=y,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=u,this.parseXml=m,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=d,this.isItStopNode=v,this.replaceEntitiesValue=I,this.readStopNodeData=A,this.saveTextToParentTag=R,this.addChild=g}};function u(y){let w=Object.keys(y);for(let S=0;S<w.length;S++){let N=w[S];this.lastEntities[N]={regex:new RegExp("&"+N+";","g"),val:y[N]}}}s(u,"Oe"),M(u,"addExternalEntities");function c(y,w,S,N,O,_,D){if(y!==void 0&&(this.options.trimValues&&!N&&(y=y.trim()),y.length>0)){D||(y=this.replaceEntitiesValue(y));let L=this.options.tagValueProcessor(w,y,S,O,_);return L==null?y:typeof L!=typeof y||L!==y?L:this.options.trimValues?Z(y,this.options.parseTagValue,this.options.numberParseOptions):y.trim()===y?Z(y,this.options.parseTagValue,this.options.numberParseOptions):y}}s(c,"Ae"),M(c,"parseTextData");function l(y){if(this.options.removeNSPrefix){let w=y.split(":"),S=y.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(y=S+w[1])}return y}s(l,"ve"),M(l,"resolveNameSpace");var p=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function d(y,w,S){if(!this.options.ignoreAttributes&&typeof y=="string"){let N=n.getAllMatches(y,p),O=N.length,_={};for(let D=0;D<O;D++){let L=this.resolveNameSpace(N[D][1]),q=N[D][4],j=this.options.attributeNamePrefix+L;if(L.length)if(this.options.transformAttributeName&&(j=this.options.transformAttributeName(j)),j==="__proto__"&&(j="#__proto__"),q!==void 0){this.options.trimValues&&(q=q.trim()),q=this.replaceEntitiesValue(q);let re=this.options.attributeValueProcessor(L,q,w);re==null?_[j]=q:typeof re!=typeof q||re!==q?_[j]=re:_[j]=Z(q,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[j]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let D={};return D[this.options.attributesGroupName]=_,D}return _}}s(d,"Ce"),M(d,"buildAttributesMap");var m=M(function(y){y=y.replace(/\r\n?/g,`
|
|
36
36
|
`);let w=new r("!xml"),S=w,N="",O="";for(let _=0;_<y.length;_++)if(y[_]==="<")if(y[_+1]==="/"){let D=f(y,">",_,"Closing Tag is not closed."),L=y.substring(_+2,D).trim();if(this.options.removeNSPrefix){let re=L.indexOf(":");re!==-1&&(L=L.substr(re+1))}this.options.transformTagName&&(L=this.options.transformTagName(L)),S&&(N=this.saveTextToParentTag(N,S,O));let q=O.substring(O.lastIndexOf(".")+1);if(L&&this.options.unpairedTags.indexOf(L)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${L}>`);let j=0;q&&this.options.unpairedTags.indexOf(q)!==-1?(j=O.lastIndexOf(".",O.lastIndexOf(".")-1),this.tagsNodeStack.pop()):j=O.lastIndexOf("."),O=O.substring(0,j),S=this.tagsNodeStack.pop(),N="",_=D}else if(y[_+1]==="?"){let D=P(y,_,!1,"?>");if(!D)throw new Error("Pi Tag is not closed.");if(N=this.saveTextToParentTag(N,S,O),!(this.options.ignoreDeclaration&&D.tagName==="?xml"||this.options.ignorePiTags)){let L=new r(D.tagName);L.add(this.options.textNodeName,""),D.tagName!==D.tagExp&&D.attrExpPresent&&(L[":@"]=this.buildAttributesMap(D.tagExp,O,D.tagName)),this.addChild(S,L,O)}_=D.closeIndex+1}else if(y.substr(_+1,3)==="!--"){let D=f(y,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let L=y.substring(_+4,D-2);N=this.saveTextToParentTag(N,S,O),S.add(this.options.commentPropName,[{[this.options.textNodeName]:L}])}_=D}else if(y.substr(_+1,2)==="!D"){let D=o(y,_);this.docTypeEntities=D.entities,_=D.i}else if(y.substr(_+1,2)==="!["){let D=f(y,"]]>",_,"CDATA is not closed.")-2,L=y.substring(_+9,D);N=this.saveTextToParentTag(N,S,O);let q=this.parseTextData(L,S.tagname,O,!0,!1,!0,!0);q==null&&(q=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:L}]):S.add(this.options.textNodeName,q),_=D+2}else{let D=P(y,_,this.options.removeNSPrefix),L=D.tagName,q=D.rawTagName,j=D.tagExp,re=D.attrExpPresent,$e=D.closeIndex;this.options.transformTagName&&(L=this.options.transformTagName(L)),S&&N&&S.tagname!=="!xml"&&(N=this.saveTextToParentTag(N,S,O,!1));let _o=S;if(_o&&this.options.unpairedTags.indexOf(_o.tagname)!==-1&&(S=this.tagsNodeStack.pop(),O=O.substring(0,O.lastIndexOf("."))),L!==w.tagname&&(O+=O?"."+L:L),this.isItStopNode(this.options.stopNodes,O,L)){let ce="";if(j.length>0&&j.lastIndexOf("/")===j.length-1)_=D.closeIndex;else if(this.options.unpairedTags.indexOf(L)!==-1)_=D.closeIndex;else{let zn=this.readStopNodeData(y,q,$e+1);if(!zn)throw new Error(`Unexpected end of ${q}`);_=zn.i,ce=zn.tagContent}let jn=new r(L);L!==j&&re&&(jn[":@"]=this.buildAttributesMap(j,O,L)),ce&&(ce=this.parseTextData(ce,L,O,!0,re,!0,!0)),O=O.substr(0,O.lastIndexOf(".")),jn.add(this.options.textNodeName,ce),this.addChild(S,jn,O)}else{if(j.length>0&&j.lastIndexOf("/")===j.length-1){L[L.length-1]==="/"?(L=L.substr(0,L.length-1),O=O.substr(0,O.length-1),j=L):j=j.substr(0,j.length-1),this.options.transformTagName&&(L=this.options.transformTagName(L));let ce=new r(L);L!==j&&re&&(ce[":@"]=this.buildAttributesMap(j,O,L)),this.addChild(S,ce,O),O=O.substr(0,O.lastIndexOf("."))}else{let ce=new r(L);this.tagsNodeStack.push(S),L!==j&&re&&(ce[":@"]=this.buildAttributesMap(j,O,L)),this.addChild(S,ce,O),S=ce}N="",_=$e}}else N+=y[_];return w.child},"parseXml");function g(y,w,S){let N=this.options.updateTag(w.tagname,S,w[":@"]);N===!1||(typeof N=="string"&&(w.tagname=N),y.addChild(w))}s(g,"Fe"),M(g,"addChild");var I=M(function(y){if(this.options.processEntities){for(let w in this.docTypeEntities){let S=this.docTypeEntities[w];y=y.replace(S.regx,S.val)}for(let w in this.lastEntities){let S=this.lastEntities[w];y=y.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let S=this.htmlEntities[w];y=y.replace(S.regex,S.val)}y=y.replace(this.ampEntity.regex,this.ampEntity.val)}return y},"replaceEntitiesValue");function R(y,w,S,N){return y&&(N===void 0&&(N=Object.keys(w.child).length===0),y=this.parseTextData(y,w.tagname,S,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,N),y!==void 0&&y!==""&&w.add(this.options.textNodeName,y),y=""),y}s(R,"_e"),M(R,"saveTextToParentTag");function v(y,w,S){let N="*."+S;for(let O in y){let _=y[O];if(N===_||w===_)return!0}return!1}s(v,"Ve"),M(v,"isItStopNode");function k(y,w,S=">"){let N,O="";for(let _=w;_<y.length;_++){let D=y[_];if(N)D===N&&(N="");else if(D==='"'||D==="'")N=D;else if(D===S[0])if(S[1]){if(y[_+1]===S[1])return{data:O,index:_}}else return{data:O,index:_};else D===" "&&(D=" ");O+=D}}s(k,"me"),M(k,"tagExpWithClosingIndex");function f(y,w,S,N){let O=y.indexOf(w,S);if(O===-1)throw new Error(N);return O+w.length-1}s(f,"T"),M(f,"findClosingIndex");function P(y,w,S,N=">"){let O=k(y,w+1,N);if(!O)return;let _=O.data,D=O.index,L=_.search(/\s/),q=_,j=!0;L!==-1&&(q=_.substring(0,L),_=_.substring(L+1).trimStart());let re=q;if(S){let $e=q.indexOf(":");$e!==-1&&(q=q.substr($e+1),j=q!==O.data.substr($e+1))}return{tagName:q,tagExp:_,closeIndex:D,attrExpPresent:j,rawTagName:re}}s(P,"k"),M(P,"readTagExp");function A(y,w,S){let N=S,O=1;for(;S<y.length;S++)if(y[S]==="<")if(y[S+1]==="/"){let _=f(y,">",S,`${w} is not closed`);if(y.substring(S+2,_).trim()===w&&(O--,O===0))return{tagContent:y.substring(N,S),i:_};S=_}else if(y[S+1]==="?")S=f(y,"?>",S+1,"StopNode is not closed.");else if(y.substr(S+1,3)==="!--")S=f(y,"-->",S+3,"StopNode is not closed.");else if(y.substr(S+1,2)==="![")S=f(y,"]]>",S,"StopNode is not closed.")-2;else{let _=P(y,S,">");_&&((_&&_.tagName)===w&&_.tagExp[_.tagExp.length-1]!=="/"&&O++,S=_.closeIndex)}}s(A,"je"),M(A,"readStopNodeData");function Z(y,w,S){if(w&&typeof y=="string"){let N=y.trim();return N==="true"?!0:N==="false"?!1:i(y,S)}else return n.isExist(y)?y:""}s(Z,"F"),M(Z,"parseValue"),e.exports=a}),sd=Le(t=>{"use strict";function e(a,u){return n(a,u)}s(e,"qe"),M(e,"prettify");function n(a,u,c){let l,p={};for(let d=0;d<a.length;d++){let m=a[d],g=r(m),I="";if(c===void 0?I=g:I=c+"."+g,g===u.textNodeName)l===void 0?l=m[g]:l+=""+m[g];else{if(g===void 0)continue;if(m[g]){let R=n(m[g],u,I),v=i(R,u);m[":@"]?o(R,m[":@"],I,u):Object.keys(R).length===1&&R[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?R=R[u.textNodeName]:Object.keys(R).length===0&&(u.alwaysCreateTextNode?R[u.textNodeName]="":R=""),p[g]!==void 0&&p.hasOwnProperty(g)?(Array.isArray(p[g])||(p[g]=[p[g]]),p[g].push(R)):u.isArray(g,I,v)?p[g]=[R]:p[g]=R}}}return typeof l=="string"?l.length>0&&(p[u.textNodeName]=l):l!==void 0&&(p[u.textNodeName]=l),p}s(n,"G"),M(n,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}s(r,"Re"),M(r,"propName");function o(a,u,c,l){if(u){let p=Object.keys(u),d=p.length;for(let m=0;m<d;m++){let g=p[m];l.isArray(g,c+"."+g,!0,!0)?a[g]=[u[g]]:a[g]=u[g]}}}s(o,"$e"),M(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"Be"),M(i,"isLeafTag"),t.prettify=e}),ad=Le(t=>{"use strict";var e=Ao(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,P){P=Object.assign({},n,P);let A=[],Z=!1,y=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let w=0;w<f.length;w++)if(f[w]==="<"&&f[w+1]==="?"){if(w+=2,w=o(f,w),w.err)return w}else if(f[w]==="<"){let S=w;if(w++,f[w]==="!"){w=i(f,w);continue}else{let N=!1;f[w]==="/"&&(N=!0,w++);let O="";for(;w<f.length&&f[w]!==">"&&f[w]!==" "&&f[w]!==" "&&f[w]!==`
|
|
37
37
|
`&&f[w]!=="\r";w++)O+=f[w];if(O=O.trim(),O[O.length-1]==="/"&&(O=O.substring(0,O.length-1),w--),!R(O)){let L;return O.trim().length===0?L="Invalid space after '<'.":L="Tag '"+O+"' is an invalid name.",g("InvalidTag",L,v(f,w))}let _=c(f,w);if(_===!1)return g("InvalidAttr","Attributes for '"+O+"' have open quote.",v(f,w));let D=_.value;if(w=_.index,D[D.length-1]==="/"){let L=w-D.length;D=D.substring(0,D.length-1);let q=p(D,P);if(q===!0)Z=!0;else return g(q.err.code,q.err.msg,v(f,L+q.err.line))}else if(N)if(_.tagClosed){if(D.trim().length>0)return g("InvalidTag","Closing tag '"+O+"' can't have attributes or invalid starting.",v(f,S));{let L=A.pop();if(O!==L.tagName){let q=v(f,L.tagStartPos);return g("InvalidTag","Expected closing tag '"+L.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+O+"'.",v(f,S))}A.length==0&&(y=!0)}}else return g("InvalidTag","Closing tag '"+O+"' doesn't have proper closing.",v(f,w));else{let L=p(D,P);if(L!==!0)return g(L.err.code,L.err.msg,v(f,w-D.length+L.err.line));if(y===!0)return g("InvalidXml","Multiple possible root nodes found.",v(f,w));P.unpairedTags.indexOf(O)!==-1||A.push({tagName:O,tagStartPos:S}),Z=!0}for(w++;w<f.length;w++)if(f[w]==="<")if(f[w+1]==="!"){w++,w=i(f,w);continue}else if(f[w+1]==="?"){if(w=o(f,++w),w.err)return w}else break;else if(f[w]==="&"){let L=m(f,w);if(L==-1)return g("InvalidChar","char '&' is not expected.",v(f,w));w=L}else if(y===!0&&!r(f[w]))return g("InvalidXml","Extra text at the end",v(f,w));f[w]==="<"&&w--}}else{if(r(f[w]))continue;return g("InvalidChar","char '"+f[w]+"' is not expected.",v(f,w))}if(Z){if(A.length==1)return g("InvalidTag","Unclosed tag '"+A[0].tagName+"'.",v(f,A[0].tagStartPos));if(A.length>0)return g("InvalidXml","Invalid '"+JSON.stringify(A.map(w=>w.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return g("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
|
|
38
|
-
`||f==="\r"}s(r,"W"),M(r,"isWhiteSpace");function o(f,P){let A=P;for(;P<f.length;P++)if(f[P]=="?"||f[P]==" "){let Z=f.substr(A,P-A);if(P>5&&Z==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",v(f,P));if(f[P]=="?"&&f[P+1]==">"){P++;break}else continue}return P}s(o,"z"),M(o,"readPI");function i(f,P){if(f.length>P+5&&f[P+1]==="-"&&f[P+2]==="-"){for(P+=3;P<f.length;P++)if(f[P]==="-"&&f[P+1]==="-"&&f[P+2]===">"){P+=2;break}}else if(f.length>P+8&&f[P+1]==="D"&&f[P+2]==="O"&&f[P+3]==="C"&&f[P+4]==="T"&&f[P+5]==="Y"&&f[P+6]==="P"&&f[P+7]==="E"){let A=1;for(P+=8;P<f.length;P++)if(f[P]==="<")A++;else if(f[P]===">"&&(A--,A===0))break}else if(f.length>P+9&&f[P+1]==="["&&f[P+2]==="C"&&f[P+3]==="D"&&f[P+4]==="A"&&f[P+5]==="T"&&f[P+6]==="A"&&f[P+7]==="["){for(P+=8;P<f.length;P++)if(f[P]==="]"&&f[P+1]==="]"&&f[P+2]===">"){P+=2;break}}return P}s(i,"K"),M(i,"readCommentAndCDATA");var a='"',u="'";function c(f,P){let A="",Z="",y=!1;for(;P<f.length;P++){if(f[P]===a||f[P]===u)Z===""?Z=f[P]:Z!==f[P]||(Z="");else if(f[P]===">"&&Z===""){y=!0;break}A+=f[P]}return Z!==""?!1:{value:A,index:P,tagClosed:y}}s(c,"Le"),M(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function p(f,P){let A=e.getAllMatches(f,l),Z={};for(let y=0;y<A.length;y++){if(A[y][1].length===0)return g("InvalidAttr","Attribute '"+A[y][2]+"' has no space in starting.",k(A[y]));if(A[y][3]!==void 0&&A[y][4]===void 0)return g("InvalidAttr","Attribute '"+A[y][2]+"' is without value.",k(A[y]));if(A[y][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+A[y][2]+"' is not allowed.",k(A[y]));let w=A[y][2];if(!I(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",k(A[y]));if(!Z.hasOwnProperty(w))Z[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",k(A[y]))}return!0}s(p,"H"),M(p,"validateAttributeString");function d(f,P){let A=/\d/;for(f[P]==="x"&&(P++,A=/[\da-fA-F]/);P<f.length;P++){if(f[P]===";")return P;if(!f[P].match(A))break}return-1}s(d,"Ue"),M(d,"validateNumberAmpersand");function m(f,P){if(P++,f[P]===";")return-1;if(f[P]==="#")return P++,d(f,P);let A=0;for(;P<f.length;P++,A++)if(!(f[P].match(/\w/)&&A<20)){if(f[P]===";")break;return-1}return P}s(m,"xe"),M(m,"validateAmpersand");function g(f,P,A){return{err:{code:f,msg:P,line:A.line||A,col:A.col}}}s(g,"a"),M(g,"getErrorObject");function I(f){return e.isName(f)}s(I,"Ge"),M(I,"validateAttrName");function R(f){return e.isName(f)}s(R,"Je"),M(R,"validateTagName");function v(f,P){let A=f.substring(0,P).split(/\r?\n/);return{line:A.length,col:A[A.length-1].length+1}}s(v,"h"),M(v,"getLineNumberForPosition");function k(f){return f.startIndex+f[1].length}s(k,"I"),M(k,"getPositionFromMatch")}),{buildOptions:ud}=td(),cd=id(),{prettify:ld}=sd(),dd=ad(),pd=class{static{s(this,"_")}static{M(this,"XMLParser")}constructor(t){this.externalEntities={},this.options=ud(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});let o=dd.validate(t,e);if(o!==!0)throw Error(`${o.err.msg}:${o.err.line}:${o.err.col}`)}let n=new cd(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(t);return this.options.preserveOrder||r===void 0?r:ld(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};Za.exports=pd;});var md={};Wa(md,{API_KEY:()=>Di,AWSLoggingPlugin:()=>wn,AmberfloMeteringInboundPolicy:()=>Ss,AmberfloMeteringPolicy:()=>Sn,ApiAuthKeyInboundPolicy:()=>As,ApiKeyInboundPolicy:()=>Cn,AuditLogDataStaxProvider:()=>En,AuditLogPlugin:()=>In,Auth0JwtInboundPolicy:()=>Ls,AwsLambdaHandlerExtensions:()=>us,BasicAuthInboundPolicy:()=>_s,BasicRateLimitInboundPolicy:()=>Eo,CachingInboundPolicy:()=>ks,ChangeMethodInboundPolicy:()=>Ds,ClearHeadersInboundPolicy:()=>Ns,ClearHeadersOutboundPolicy:()=>Ms,ClerkJwtInboundPolicy:()=>Us,CognitoJwtInboundPolicy:()=>Hs,CompositeInboundPolicy:()=>Zs,ConfigurationError:()=>h,ContentTypes:()=>qt,ContextData:()=>le,CryptoBeta:()=>$n,CurityPhantomTokenInboundPolicy:()=>qs,DataDogLoggingPlugin:()=>on,DataDogMetricsPlugin:()=>Rn,DynaTraceLoggingPlugin:()=>fn,DynatraceMetricsPlugin:()=>Pn,FirebaseJwtInboundPolicy:()=>$s,FormDataToJsonInboundPolicy:()=>Fs,GeoFilterInboundPolicy:()=>Bs,GoogleCloudLoggingPlugin:()=>tn,Handler:()=>mn,HttpProblems:()=>T,HttpStatusCode:()=>Bt,InboundPolicy:()=>de,JWTScopeValidationInboundPolicy:()=>js,KeyValueStore:()=>Bn,LokiLoggingPlugin:()=>hn,LookupResult:()=>Ke,MemoryZoneReadThroughCache:()=>J,MockApiInboundPolicy:()=>Vs,MoesifInboundPolicy:()=>Qs,MonetizationInboundPolicy:()=>Ln,OktaJwtInboundPolicy:()=>na,OpenIdJwtInboundPolicy:()=>X,OutboundPolicy:()=>Ze,ProblemResponseFormatter:()=>ve,PropelAuthJwtInboundPolicy:()=>oa,RateLimitInboundPolicy:()=>Eo,ReadmeMetricsInboundPolicy:()=>ca,RemoveHeadersInboundPolicy:()=>la,RemoveHeadersOutboundPolicy:()=>da,RemoveQueryParamsInboundPolicy:()=>pa,ReplaceStringOutboundPolicy:()=>ma,RequestSizeLimitInboundPolicy:()=>fa,RequestValidationInboundPolicy:()=>vo,RequireOriginInboundPolicy:()=>Ia,ResponseSendingEvent:()=>ze,ResponseSentEvent:()=>Ve,Router:()=>Je,RuntimeError:()=>C,SYSTEM_LOGGER:()=>yt,SchemaBasedRequestValidation:()=>Ea,ServiceProviderImpl:()=>Zn,SetBodyInboundPolicy:()=>xa,SetHeadersInboundPolicy:()=>va,SetHeadersOutboundPolicy:()=>Ta,SetQueryParamsInboundPolicy:()=>Sa,SetStatusOutboundPolicy:()=>Oa,SleepInboundPolicy:()=>Ca,StripeMeteringPlugin:()=>go,StripeWebhookVerificationInboundPolicy:()=>tt,SumoLogicLoggingPlugin:()=>yn,SupabaseJwtInboundPolicy:()=>Aa,SystemLogMap:()=>F,SystemRouteName:()=>he,UpstreamAzureAdServiceAuthInboundPolicy:()=>La,UpstreamFirebaseAdminAuthInboundPolicy:()=>ka,UpstreamFirebaseUserAuthInboundPolicy:()=>Da,UpstreamGcpJwtInboundPolicy:()=>Na,UpstreamGcpServiceAuthInboundPolicy:()=>Ua,VMWareLogInsightLoggingPlugin:()=>bn,ValidateJsonSchemaInbound:()=>Ha,XmlToJsonOutboundPolicy:()=>Fa,ZoneCache:()=>Ee,ZuploRequest:()=>z,awsLambdaHandler:()=>cs,environment:()=>ne,getIdForParameterSchema:()=>Un,getIdForRefSchema:()=>ya,getIdForRequestBodySchema:()=>Hn,getRawOperationDataIdentifierName:()=>ha,httpStatuses:()=>jt,isRestrictedEnvVariableName:()=>Zr,isZuploReadableEnvVariableName:()=>qr,openApiSpecHandler:()=>ls,originalFetch:()=>Ye,purgeGatewayCache:()=>Yi,redirectHandler:()=>ds,sanitizedIdentifierName:()=>Ae,serialize:()=>$t,setMoesifContext:()=>Ys,urlForwardHandler:()=>ps,urlRewriteHandler:()=>ms,webSocketHandler:()=>gs,webSocketPipelineHandler:()=>ys});module.exports=Ka(md);var $=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},C=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"}},h=class extends C{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},Ct=class extends C{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var E=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 $("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 meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var At=globalThis,Do=At.caches;if(Do){let t=Do.open;At.caches.open=function(e){let n=E.instance.deploymentName??E.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete At.caches.default,Object.freeze(At.caches)}var No=new Map,Vn=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)})}},Be=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=No.get(e);r||(r=new Vn(n),No.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 Gn="__zuplo-expiry-header",Ee=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(Gn);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(Gn,`${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(Gn,`${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 J=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Be(r),this.#n=new Ee(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Mo="zuplo-request-id",ut="zp-rid",Uo="zp-body-removed",je="cf-ray",Wn="cf-ipcity",Kn="cf-ipcontinent",Jn="cf-ipcountry",Yn="cf-iplongitude",Qn="cf-iplatitude",Ho="zp-ipcity",Zo="zp-ipcontinent",qo="zp-ipcountry",$o="zp-iplongitude",Fo="zp-iplatitude",Bo="true-client-ip",Xn="zp-asn",er="zp-asorg",tr="zp-colo",nr="zp-postalcode",rr="zp-metrocode",or="zp-region",ir="zp-regioncode",sr="zp-timezone",jo=[Wn,Kn,Jn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr],zo=["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"],ct="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Lt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Fi=_e(De());var dt=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 C("Error in custom 'problemResponseFormat'",{cause:i})}})}},ve=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await dt.problemResponseFormat(e,n,r)}};function Ht(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ht(n)}return Object.freeze(t)}s(Ht,"deepFreeze");var z=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){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Ht(this.#e)}get params(){return Ht(this.#t)}user};var Ne=class{static{s(this,"RuntimePlugin")}},Re=class extends Ne{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},pt={},Te=[],li=[],di=[],pi=[];var Zt={addPlugin(t){Te.push(t)},addRequestHook(t){li.push(t)},addResponseSendingHook(t){di.push(t)},addResponseSendingFinalHook(t){pi.push(t)}},mi=s(async(t,e)=>{let n=t;for(let r of li){let o=await r(n,e);if(o instanceof z)n=o;else{if(o instanceof Response)return o;throw new h(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),gi=s(async(t,e,n)=>{let r=t;for(let o of di){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new h(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),fi=s(async(t,e,n)=>{for(let r of pi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function hi(t=()=>Promise.resolve()){await t(Zt),pt.value=Zt;for(let e of Te)e instanceof Re&&await e.initialize(Zt);dt.setProblemResponseFormat(Zt.problemResponseFormat)}s(hi,"initializeRuntime");var qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function $t(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(qt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(qt.Json)||!e?JSON.stringify(t):t}s($t,"serialize");function mt(t){return Y.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Y.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(mt,"isSystemRoute");var G=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}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=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async R=>{let v=a.pop();return v?v(o,i,n,u):await this.#e(async f=>{let P=await r(f,i);return nc(P)},n)(R,i)},"nextPipe"),l=await u(o),p=new URL(o.url);if(mt(p)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let d=new ze(o,l);i.dispatchEvent(d);let m=ee.getContextExtensions(i),g=m.latestRequest,I;try{I=await d.mutableResponse}catch(R){return i.log.error(R),n.errorHandler(o,i,R)}try{I=await m.onResponseSending(I,g,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}try{I=await gi(I,g,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}i.dispatchEvent(new Ve(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await fi(l,g,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return I}};function nc(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response($t(t),{headers:{"content-type":"application/json"}})}s(nc,"resultToResponse");var Se=class extends Ne{static{s(this,"MetricsPlugin")}};var F=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 $(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var B=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 Ft=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=E.instance.loggingId,this.#e=e,this.#t=new B("ellie-metrics-transport",10,this.dispatchFunction,F.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}=E.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":E.instance.deploymentName??"unknown","user-agent":E.instance.systemUserAgent}});if(!u.ok){let c=await u.text();F.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var V=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=gt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},gt={name:"__system-no-version",pathPrefix:""};var te=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(Bo)??void 0,l=e.incomingRequestProperties,p;e.route instanceof V&&(p=e.route.systemRouteName);let d=ee.getContextExtensions(e).latestRequest,m={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:p,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:d.user?.sub,clientIp:c},g=[];return g.push(new Ft(e)),Te.forEach(I=>{if(I instanceof Se){let R=I.getTransport();g.push(R)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var he=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(he||{});var fr=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 T.notFound(i,a);let l=E.instance.build,p={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},d=i.url.toString().split("?");return d.length>0&&new URLSearchParams(d[1]).get("system_log")==="true"&&F.getLogger(a).error("Test System Log",p),new Response(JSON.stringify(p,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new G({processors:[te],handler:n,gateway:e}),o=new V({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var Bt=(b=>(b[b.CONTINUE=100]="CONTINUE",b[b.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",b[b.PROCESSING=102]="PROCESSING",b[b.EARLY_HINTS=103]="EARLY_HINTS",b[b.OK=200]="OK",b[b.CREATED=201]="CREATED",b[b.ACCEPTED=202]="ACCEPTED",b[b.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",b[b.NO_CONTENT=204]="NO_CONTENT",b[b.RESET_CONTENT=205]="RESET_CONTENT",b[b.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",b[b.MULTI_STATUS=207]="MULTI_STATUS",b[b.ALREADY_REPORTED=208]="ALREADY_REPORTED",b[b.IM_USED=226]="IM_USED",b[b.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",b[b.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",b[b.FOUND=302]="FOUND",b[b.SEE_OTHER=303]="SEE_OTHER",b[b.NOT_MODIFIED=304]="NOT_MODIFIED",b[b.USE_PROXY=305]="USE_PROXY",b[b.SWITCH_PROXY=306]="SWITCH_PROXY",b[b.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",b[b.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",b[b.BAD_REQUEST=400]="BAD_REQUEST",b[b.UNAUTHORIZED=401]="UNAUTHORIZED",b[b.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",b[b.FORBIDDEN=403]="FORBIDDEN",b[b.NOT_FOUND=404]="NOT_FOUND",b[b.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",b[b.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",b[b.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",b[b.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",b[b.CONFLICT=409]="CONFLICT",b[b.GONE=410]="GONE",b[b.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",b[b.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",b[b.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",b[b.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",b[b.URI_TOO_LONG=414]="URI_TOO_LONG",b[b.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",b[b.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",b[b.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",b[b.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",b[b.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",b[b.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",b[b.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",b[b.LOCKED=423]="LOCKED",b[b.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",b[b.TOO_EARLY=425]="TOO_EARLY",b[b.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",b[b.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",b[b.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",b[b.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",b[b.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",b[b.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",b[b.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",b[b.BAD_GATEWAY=502]="BAD_GATEWAY",b[b.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",b[b.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",b[b.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",b[b.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",b[b.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",b[b.LOOP_DETECTED=508]="LOOP_DETECTED",b[b.NOT_EXTENDED=510]="NOT_EXTENDED",b[b.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",b))(Bt||{}),yi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var rc={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"},jt=rc;function oc(t){return`${new URL(t.url).pathname}`}s(oc,"instance");function ic(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}s(ic,"trace");var sc=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:oc(e),trace:ic(e,n),...r},additionalHeaders:o,statusText:jt[t.status]}),"merge"),hr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ve.format(e,n,r):ve.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:yi[e],...n}}},T=class extends hr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=sc(this.getProblemFromStatus(e),n,r,o,i);return ve.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:ac}=Object.prototype,{propertyIsEnumerable:uc}=Object.prototype;function yr(t){return ac.call(t)}s(yr,"toString");function se(t){return typeof t=="string"}s(se,"isString");function Ge(t){return se(t)&&t!==""}s(Ge,"isNonEmptyString");function bi(t){return yr(t)==="[object RegExp]"}s(bi,"isRegexp");function wi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>uc.call(t,e))]}s(wi,"getOwnEnumerableKeys");function Me(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Me,"isObject");function br(t){return typeof t=="number"&&!isNaN(t)}s(br,"isNumber");function wr(t){return t===!0||t===!1}s(wr,"isBoolean");function Ri(t){return typeof t>"u"}s(Ri,"isUndefined");function Pi(t){return Ri(t)||t===null}s(Pi,"isUndefinedOrNull");function ft(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ft,"isErrorLike");var Ei=new Map;function zt(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=Ei.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 Ei.set(t,r),r}s(zt,"statusCodesStringToNumberArray");function Ue(t,e,n){if(!e.startsWith("."))throw new h(`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 C(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ue,"getValueFromRequestUser");function He(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new h("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new h(`Expected type of string, received type '${typeof t}'`)}s(He,"parseValueToStringArray");function Ii(t){if(t==null)return[];if(!Array.isArray(t))throw new h(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Me(n))throw new h(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new h("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!br(n.maxAge))throw new h(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!wr(n.allowCredentials))throw new h("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=Rr(n,"allowedHeaders"),o=Rr(n,"allowedMethods"),i=Rr(n,"exposeHeaders"),a;try{a=He(n.allowedOrigins)}catch(c){throw new h(`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(Ii,"parseCorsPolicies");function Rr(t,e){let n;if(t[e]!==void 0)try{n=He(t[e])}catch(r){throw new h(`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(Rr,"parseOptionalProperty");var Vt=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"),Gt=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 Pr=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"),p=a.headers.get("access-control-request-headers"),d=a.headers.get("origin");if(d===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=cc(l,p,d,g,n);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new G({processors:[te],handler:r,gateway:e}),i=new V({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),cc=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 h(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Vt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var xi=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 G({processors:[te],handler:n,gateway:e}),o=new V({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 Er=new V({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),vi=s((t,e)=>{let n=s(async(o,i)=>{let a=pt.value?.notFoundHandler;if(a){let u=ee.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new G({processors:[te],handler:n,gateway:e});t.addRoute(Er,r.execute)},"registerNotMatchedHandler");var lc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ti=s(t=>{lc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let p=await r(t),d=new Headers(p.headers);return Ti(d),new Response(p.body,{status:p.status,statusText:p.statusText,headers:d,webSocket:p.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=dc(o,n.routeData.corsPolicies),u=pc(t,a),c=new Headers(i.headers);return Ti(c),Object.entries(u).forEach(([p,d])=>{c.set(p,d)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),dc=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 h(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),pc=s((t,e)=>{let n=Vt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var Ir=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new G({processors:[Wt],handler:n,gateway:e}),o=new V({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Kt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new C(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},de=class extends Kt{static{s(this,"InboundPolicy")}},Ze=class extends Kt{static{s(this,"OutboundPolicy")}};var Tr=class extends de{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Sr=class extends Ze{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},xr=new Map;function ht(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!xr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new h(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof de)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Tr(u,a.handler.options,a.name);else throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new h(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);xr.set(a.name,c)}),n.map(i=>{let a=xr.get(i);if(a===void 0)throw new C("Internal error. Policy not found in cache.");return a})}s(ht,"getInboundPolicyInstances");var vr=new Map;function mc(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!vr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new h(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ze)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new Sr(a,i.handler.options,i.name);else throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new h(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);vr.set(i.name,u)}),n.map(o=>{let i=vr.get(o);if(i===void 0)throw new C("Internal error. Policy not found in cache.");return i})}s(mc,"getOutboundPolicyInstances");var Or=s(t=>async(e,n)=>{let r=ee.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);if(u instanceof z)i=u;else if(u instanceof Request)i=new z(u);else{if(u instanceof Response)return u;throw new h(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),gc=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);if(!(u instanceof Response))throw new h(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Jt=s(async(t,e,n,r)=>{let o=ht(e.route,n.routeData.policies),i=mc(e.route,n.routeData.policies);return Oi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Si({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Oi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Si,"createInternalPolicyProcessor");async function Oi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Or(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=gc(r),p;return E.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?p=l(c,t,e):p=c.ok?l(c,t,e):c,p}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Oi,"executePolicyProcessor");function Ci(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||fc,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]=hc(l,o)}i=u+1}return n}s(Ci,"parse");function fc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(fc,"decode");function hc(t,e){try{return e(t)}catch{return t}}s(hc,"tryDecode");function Ai(t,e){try{let n=/v\d+(-\d+)?/g,o=Ci(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Ai,"devPortalBaseURL");var Li="/__zuplo/dev-portal",yc="dev-portal-id",bc="dev-portal-host",wc="zp-account",Rc="zp-project",Pc="dev-portal-build",Ec=`
|
|
38
|
+
`||f==="\r"}s(r,"W"),M(r,"isWhiteSpace");function o(f,P){let A=P;for(;P<f.length;P++)if(f[P]=="?"||f[P]==" "){let Z=f.substr(A,P-A);if(P>5&&Z==="xml")return g("InvalidXml","XML declaration allowed only at the start of the document.",v(f,P));if(f[P]=="?"&&f[P+1]==">"){P++;break}else continue}return P}s(o,"z"),M(o,"readPI");function i(f,P){if(f.length>P+5&&f[P+1]==="-"&&f[P+2]==="-"){for(P+=3;P<f.length;P++)if(f[P]==="-"&&f[P+1]==="-"&&f[P+2]===">"){P+=2;break}}else if(f.length>P+8&&f[P+1]==="D"&&f[P+2]==="O"&&f[P+3]==="C"&&f[P+4]==="T"&&f[P+5]==="Y"&&f[P+6]==="P"&&f[P+7]==="E"){let A=1;for(P+=8;P<f.length;P++)if(f[P]==="<")A++;else if(f[P]===">"&&(A--,A===0))break}else if(f.length>P+9&&f[P+1]==="["&&f[P+2]==="C"&&f[P+3]==="D"&&f[P+4]==="A"&&f[P+5]==="T"&&f[P+6]==="A"&&f[P+7]==="["){for(P+=8;P<f.length;P++)if(f[P]==="]"&&f[P+1]==="]"&&f[P+2]===">"){P+=2;break}}return P}s(i,"K"),M(i,"readCommentAndCDATA");var a='"',u="'";function c(f,P){let A="",Z="",y=!1;for(;P<f.length;P++){if(f[P]===a||f[P]===u)Z===""?Z=f[P]:Z!==f[P]||(Z="");else if(f[P]===">"&&Z===""){y=!0;break}A+=f[P]}return Z!==""?!1:{value:A,index:P,tagClosed:y}}s(c,"Le"),M(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function p(f,P){let A=e.getAllMatches(f,l),Z={};for(let y=0;y<A.length;y++){if(A[y][1].length===0)return g("InvalidAttr","Attribute '"+A[y][2]+"' has no space in starting.",k(A[y]));if(A[y][3]!==void 0&&A[y][4]===void 0)return g("InvalidAttr","Attribute '"+A[y][2]+"' is without value.",k(A[y]));if(A[y][3]===void 0&&!P.allowBooleanAttributes)return g("InvalidAttr","boolean attribute '"+A[y][2]+"' is not allowed.",k(A[y]));let w=A[y][2];if(!I(w))return g("InvalidAttr","Attribute '"+w+"' is an invalid name.",k(A[y]));if(!Z.hasOwnProperty(w))Z[w]=1;else return g("InvalidAttr","Attribute '"+w+"' is repeated.",k(A[y]))}return!0}s(p,"H"),M(p,"validateAttributeString");function d(f,P){let A=/\d/;for(f[P]==="x"&&(P++,A=/[\da-fA-F]/);P<f.length;P++){if(f[P]===";")return P;if(!f[P].match(A))break}return-1}s(d,"Ue"),M(d,"validateNumberAmpersand");function m(f,P){if(P++,f[P]===";")return-1;if(f[P]==="#")return P++,d(f,P);let A=0;for(;P<f.length;P++,A++)if(!(f[P].match(/\w/)&&A<20)){if(f[P]===";")break;return-1}return P}s(m,"xe"),M(m,"validateAmpersand");function g(f,P,A){return{err:{code:f,msg:P,line:A.line||A,col:A.col}}}s(g,"a"),M(g,"getErrorObject");function I(f){return e.isName(f)}s(I,"Ge"),M(I,"validateAttrName");function R(f){return e.isName(f)}s(R,"Je"),M(R,"validateTagName");function v(f,P){let A=f.substring(0,P).split(/\r?\n/);return{line:A.length,col:A[A.length-1].length+1}}s(v,"h"),M(v,"getLineNumberForPosition");function k(f){return f.startIndex+f[1].length}s(k,"I"),M(k,"getPositionFromMatch")}),{buildOptions:ud}=td(),cd=id(),{prettify:ld}=sd(),dd=ad(),pd=class{static{s(this,"_")}static{M(this,"XMLParser")}constructor(t){this.externalEntities={},this.options=ud(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});let o=dd.validate(t,e);if(o!==!0)throw Error(`${o.err.msg}:${o.err.line}:${o.err.col}`)}let n=new cd(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(t);return this.options.preserveOrder||r===void 0?r:ld(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};Za.exports=pd;});var md={};Wa(md,{API_KEY:()=>Di,AWSLoggingPlugin:()=>wn,AmberfloMeteringInboundPolicy:()=>Ss,AmberfloMeteringPolicy:()=>Sn,ApiAuthKeyInboundPolicy:()=>As,ApiKeyInboundPolicy:()=>Cn,AuditLogDataStaxProvider:()=>En,AuditLogPlugin:()=>In,Auth0JwtInboundPolicy:()=>Ls,AwsLambdaHandlerExtensions:()=>us,BasicAuthInboundPolicy:()=>_s,BasicRateLimitInboundPolicy:()=>Eo,CachingInboundPolicy:()=>ks,ChangeMethodInboundPolicy:()=>Ds,ClearHeadersInboundPolicy:()=>Ns,ClearHeadersOutboundPolicy:()=>Ms,ClerkJwtInboundPolicy:()=>Us,CognitoJwtInboundPolicy:()=>Hs,CompositeInboundPolicy:()=>Zs,ConfigurationError:()=>h,ContentTypes:()=>qt,ContextData:()=>le,CryptoBeta:()=>$n,CurityPhantomTokenInboundPolicy:()=>qs,DataDogLoggingPlugin:()=>on,DataDogMetricsPlugin:()=>Rn,DynaTraceLoggingPlugin:()=>fn,DynatraceMetricsPlugin:()=>Pn,FirebaseJwtInboundPolicy:()=>$s,FormDataToJsonInboundPolicy:()=>Fs,GeoFilterInboundPolicy:()=>Bs,GoogleCloudLoggingPlugin:()=>tn,Handler:()=>mn,HttpProblems:()=>T,HttpStatusCode:()=>Bt,InboundPolicy:()=>de,JWTScopeValidationInboundPolicy:()=>js,KeyValueStore:()=>Bn,LokiLoggingPlugin:()=>hn,LookupResult:()=>Je,MemoryZoneReadThroughCache:()=>K,MockApiInboundPolicy:()=>Vs,MoesifInboundPolicy:()=>Qs,MonetizationInboundPolicy:()=>Ln,OktaJwtInboundPolicy:()=>na,OpenIdJwtInboundPolicy:()=>X,OutboundPolicy:()=>Ze,ProblemResponseFormatter:()=>ve,PropelAuthJwtInboundPolicy:()=>oa,RateLimitInboundPolicy:()=>Eo,ReadmeMetricsInboundPolicy:()=>ca,RemoveHeadersInboundPolicy:()=>la,RemoveHeadersOutboundPolicy:()=>da,RemoveQueryParamsInboundPolicy:()=>pa,ReplaceStringOutboundPolicy:()=>ma,RequestSizeLimitInboundPolicy:()=>fa,RequestValidationInboundPolicy:()=>vo,RequireOriginInboundPolicy:()=>Ia,ResponseSendingEvent:()=>ze,ResponseSentEvent:()=>Ve,Router:()=>Ke,RuntimeError:()=>C,SYSTEM_LOGGER:()=>yt,SchemaBasedRequestValidation:()=>Ea,ServiceProviderImpl:()=>Zn,SetBodyInboundPolicy:()=>xa,SetHeadersInboundPolicy:()=>va,SetHeadersOutboundPolicy:()=>Ta,SetQueryParamsInboundPolicy:()=>Sa,SetStatusOutboundPolicy:()=>Oa,SleepInboundPolicy:()=>Ca,StripeMeteringPlugin:()=>go,StripeWebhookVerificationInboundPolicy:()=>tt,SumoLogicLoggingPlugin:()=>yn,SupabaseJwtInboundPolicy:()=>Aa,SystemLogMap:()=>F,SystemRouteName:()=>he,UpstreamAzureAdServiceAuthInboundPolicy:()=>La,UpstreamFirebaseAdminAuthInboundPolicy:()=>ka,UpstreamFirebaseUserAuthInboundPolicy:()=>Da,UpstreamGcpJwtInboundPolicy:()=>Na,UpstreamGcpServiceAuthInboundPolicy:()=>Ua,VMWareLogInsightLoggingPlugin:()=>bn,ValidateJsonSchemaInbound:()=>Ha,XmlToJsonOutboundPolicy:()=>Fa,ZoneCache:()=>Ee,ZuploRequest:()=>z,awsLambdaHandler:()=>cs,environment:()=>ne,getIdForParameterSchema:()=>Un,getIdForRefSchema:()=>ya,getIdForRequestBodySchema:()=>Hn,getRawOperationDataIdentifierName:()=>ha,httpStatuses:()=>jt,isRestrictedEnvVariableName:()=>Zr,isZuploReadableEnvVariableName:()=>qr,openApiSpecHandler:()=>ls,originalFetch:()=>Ye,purgeGatewayCache:()=>Yi,redirectHandler:()=>ds,sanitizedIdentifierName:()=>Ae,serialize:()=>$t,setMoesifContext:()=>Ys,urlForwardHandler:()=>ps,urlRewriteHandler:()=>ms,webSocketHandler:()=>gs,webSocketPipelineHandler:()=>ys});module.exports=Ja(md);var $=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},C=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"}},h=class extends C{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},Ct=class extends C{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var E=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 $("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 meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var At=globalThis,Do=At.caches;if(Do){let t=Do.open;At.caches.open=function(e){let n=E.instance.deploymentName??E.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete At.caches.default,Object.freeze(At.caches)}var No=new Map,Vn=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)})}},Be=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=No.get(e);r||(r=new Vn(n),No.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 Gn="__zuplo-expiry-header",Ee=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(Gn);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(Gn,`${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(Gn,`${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 K=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Be(r),this.#n=new Ee(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Mo="zuplo-request-id",ut="zp-rid",Uo="zp-body-removed",je="cf-ray",Wn="cf-ipcity",Jn="cf-ipcontinent",Kn="cf-ipcountry",Yn="cf-iplongitude",Qn="cf-iplatitude",Ho="zp-ipcity",Zo="zp-ipcontinent",qo="zp-ipcountry",$o="zp-iplongitude",Fo="zp-iplatitude",Bo="true-client-ip",Xn="zp-asn",er="zp-asorg",tr="zp-colo",nr="zp-postalcode",rr="zp-metrocode",or="zp-region",ir="zp-regioncode",sr="zp-timezone",jo=[Wn,Jn,Kn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr],zo=["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"],ct="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Lt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Fi=_e(De());var dt=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 C("Error in custom 'problemResponseFormat'",{cause:i})}})}},ve=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await dt.problemResponseFormat(e,n,r)}};function Ht(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ht(n)}return Object.freeze(t)}s(Ht,"deepFreeze");var z=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){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Ht(this.#e)}get params(){return Ht(this.#t)}user};var Ne=class{static{s(this,"RuntimePlugin")}},Re=class extends Ne{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},pt={},Te=[],li=[],di=[],pi=[];var Zt={addPlugin(t){Te.push(t)},addRequestHook(t){li.push(t)},addResponseSendingHook(t){di.push(t)},addResponseSendingFinalHook(t){pi.push(t)}},mi=s(async(t,e)=>{let n=t;for(let r of li){let o=await r(n,e);if(o instanceof z)n=o;else{if(o instanceof Response)return o;throw new h(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),gi=s(async(t,e,n)=>{let r=t;for(let o of di){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new h(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),fi=s(async(t,e,n)=>{for(let r of pi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function hi(t=()=>Promise.resolve()){await t(Zt),pt.value=Zt;for(let e of Te)e instanceof Re&&await e.initialize(Zt);dt.setProblemResponseFormat(Zt.problemResponseFormat)}s(hi,"initializeRuntime");var qt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function $t(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(qt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(qt.Json)||!e?JSON.stringify(t):t}s($t,"serialize");function mt(t){return Y.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Y.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(mt,"isSystemRoute");var G=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}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=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async R=>{let v=a.pop();return v?v(o,i,n,u):await this.#e(async f=>{let P=await r(f,i);return nc(P)},n)(R,i)},"nextPipe"),l=await u(o),p=new URL(o.url);if(mt(p)&&E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let d=new ze(o,l);i.dispatchEvent(d);let m=ee.getContextExtensions(i),g=m.latestRequest,I;try{I=await d.mutableResponse}catch(R){return i.log.error(R),n.errorHandler(o,i,R)}try{I=await m.onResponseSending(I,g,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}try{I=await gi(I,g,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}i.dispatchEvent(new Ve(o,I));try{await m.onResponseSendingFinal(l,g,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await fi(l,g,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return I}};function nc(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response($t(t),{headers:{"content-type":"application/json"}})}s(nc,"resultToResponse");var Se=class extends Ne{static{s(this,"MetricsPlugin")}};var F=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 $(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var B=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 Ft=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=E.instance.loggingId,this.#e=e,this.#t=new B("ellie-metrics-transport",10,this.dispatchFunction,F.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}=E.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":E.instance.deploymentName??"unknown","user-agent":E.instance.systemUserAgent}});if(!u.ok){let c=await u.text();F.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var V=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=gt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},gt={name:"__system-no-version",pathPrefix:""};var te=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(Bo)??void 0,l=e.incomingRequestProperties,p;e.route instanceof V&&(p=e.route.systemRouteName);let d=ee.getContextExtensions(e).latestRequest,m={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:p,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:d.user?.sub,clientIp:c},g=[];return g.push(new Ft(e)),Te.forEach(I=>{if(I instanceof Se){let R=I.getTransport();g.push(R)}}),g.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var he=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(he||{});var fr=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 T.notFound(i,a);let l=E.instance.build,p={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},d=i.url.toString().split("?");return d.length>0&&new URLSearchParams(d[1]).get("system_log")==="true"&&F.getLogger(a).error("Test System Log",p),new Response(JSON.stringify(p,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new G({processors:[te],handler:n,gateway:e}),o=new V({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var Bt=(b=>(b[b.CONTINUE=100]="CONTINUE",b[b.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",b[b.PROCESSING=102]="PROCESSING",b[b.EARLY_HINTS=103]="EARLY_HINTS",b[b.OK=200]="OK",b[b.CREATED=201]="CREATED",b[b.ACCEPTED=202]="ACCEPTED",b[b.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",b[b.NO_CONTENT=204]="NO_CONTENT",b[b.RESET_CONTENT=205]="RESET_CONTENT",b[b.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",b[b.MULTI_STATUS=207]="MULTI_STATUS",b[b.ALREADY_REPORTED=208]="ALREADY_REPORTED",b[b.IM_USED=226]="IM_USED",b[b.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",b[b.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",b[b.FOUND=302]="FOUND",b[b.SEE_OTHER=303]="SEE_OTHER",b[b.NOT_MODIFIED=304]="NOT_MODIFIED",b[b.USE_PROXY=305]="USE_PROXY",b[b.SWITCH_PROXY=306]="SWITCH_PROXY",b[b.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",b[b.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",b[b.BAD_REQUEST=400]="BAD_REQUEST",b[b.UNAUTHORIZED=401]="UNAUTHORIZED",b[b.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",b[b.FORBIDDEN=403]="FORBIDDEN",b[b.NOT_FOUND=404]="NOT_FOUND",b[b.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",b[b.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",b[b.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",b[b.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",b[b.CONFLICT=409]="CONFLICT",b[b.GONE=410]="GONE",b[b.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",b[b.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",b[b.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",b[b.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",b[b.URI_TOO_LONG=414]="URI_TOO_LONG",b[b.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",b[b.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",b[b.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",b[b.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",b[b.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",b[b.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",b[b.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",b[b.LOCKED=423]="LOCKED",b[b.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",b[b.TOO_EARLY=425]="TOO_EARLY",b[b.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",b[b.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",b[b.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",b[b.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",b[b.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",b[b.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",b[b.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",b[b.BAD_GATEWAY=502]="BAD_GATEWAY",b[b.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",b[b.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",b[b.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",b[b.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",b[b.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",b[b.LOOP_DETECTED=508]="LOOP_DETECTED",b[b.NOT_EXTENDED=510]="NOT_EXTENDED",b[b.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",b))(Bt||{}),yi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var rc={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"},jt=rc;function oc(t){return`${new URL(t.url).pathname}`}s(oc,"instance");function ic(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:E.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}s(ic,"trace");var sc=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:oc(e),trace:ic(e,n),...r},additionalHeaders:o,statusText:jt[t.status]}),"merge"),hr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ve.format(e,n,r):ve.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:yi[e],...n}}},T=class extends hr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=sc(this.getProblemFromStatus(e),n,r,o,i);return ve.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:ac}=Object.prototype,{propertyIsEnumerable:uc}=Object.prototype;function yr(t){return ac.call(t)}s(yr,"toString");function se(t){return typeof t=="string"}s(se,"isString");function Ge(t){return se(t)&&t!==""}s(Ge,"isNonEmptyString");function bi(t){return yr(t)==="[object RegExp]"}s(bi,"isRegexp");function wi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>uc.call(t,e))]}s(wi,"getOwnEnumerableKeys");function Me(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Me,"isObject");function br(t){return typeof t=="number"&&!isNaN(t)}s(br,"isNumber");function wr(t){return t===!0||t===!1}s(wr,"isBoolean");function Ri(t){return typeof t>"u"}s(Ri,"isUndefined");function Pi(t){return Ri(t)||t===null}s(Pi,"isUndefinedOrNull");function ft(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ft,"isErrorLike");var Ei=new Map;function zt(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=Ei.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 Ei.set(t,r),r}s(zt,"statusCodesStringToNumberArray");function Ue(t,e,n){if(!e.startsWith("."))throw new h(`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 C(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ue,"getValueFromRequestUser");function He(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new h("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new h(`Expected type of string, received type '${typeof t}'`)}s(He,"parseValueToStringArray");function Ii(t){if(t==null)return[];if(!Array.isArray(t))throw new h(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Me(n))throw new h(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new h("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!br(n.maxAge))throw new h(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!wr(n.allowCredentials))throw new h("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=Rr(n,"allowedHeaders"),o=Rr(n,"allowedMethods"),i=Rr(n,"exposeHeaders"),a;try{a=He(n.allowedOrigins)}catch(c){throw new h(`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(Ii,"parseCorsPolicies");function Rr(t,e){let n;if(t[e]!==void 0)try{n=He(t[e])}catch(r){throw new h(`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(Rr,"parseOptionalProperty");var Vt=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"),Gt=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 Pr=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"),p=a.headers.get("access-control-request-headers"),d=a.headers.get("origin");if(d===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,c);if(!m)return T.notFound(a,u);let g=m.routeConfiguration,I=cc(l,p,d,g,n);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new G({processors:[te],handler:r,gateway:e}),i=new V({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),cc=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 h(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Vt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var xi=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 G({processors:[te],handler:n,gateway:e}),o=new V({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 Er=new V({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),vi=s((t,e)=>{let n=s(async(o,i)=>{let a=pt.value?.notFoundHandler;if(a){let u=ee.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new G({processors:[te],handler:n,gateway:e});t.addRoute(Er,r.execute)},"registerNotMatchedHandler");var lc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ti=s(t=>{lc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let p=await r(t),d=new Headers(p.headers);return Ti(d),new Response(p.body,{status:p.status,statusText:p.statusText,headers:d,webSocket:p.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new $(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=dc(o,n.routeData.corsPolicies),u=pc(t,a),c=new Headers(i.headers);return Ti(c),Object.entries(u).forEach(([p,d])=>{c.set(p,d)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),dc=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 h(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),pc=s((t,e)=>{let n=Vt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var Ir=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new G({processors:[Wt],handler:n,gateway:e}),o=new V({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Jt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new C(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},de=class extends Jt{static{s(this,"InboundPolicy")}},Ze=class extends Jt{static{s(this,"OutboundPolicy")}};var Tr=class extends de{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Sr=class extends Ze{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},xr=new Map;function ht(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!xr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new h(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof de)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Tr(u,a.handler.options,a.name);else throw new h(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new h(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);xr.set(a.name,c)}),n.map(i=>{let a=xr.get(i);if(a===void 0)throw new C("Internal error. Policy not found in cache.");return a})}s(ht,"getInboundPolicyInstances");var vr=new Map;function mc(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!vr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new h(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ze)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new Sr(a,i.handler.options,i.name);else throw new h(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new h(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);vr.set(i.name,u)}),n.map(o=>{let i=vr.get(o);if(i===void 0)throw new C("Internal error. Policy not found in cache.");return i})}s(mc,"getOutboundPolicyInstances");var Or=s(t=>async(e,n)=>{let r=ee.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);if(u instanceof z)i=u;else if(u instanceof Request)i=new z(u);else{if(u instanceof Response)return u;throw new h(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),gc=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);if(!(u instanceof Response))throw new h(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Kt=s(async(t,e,n,r)=>{let o=ht(e.route,n.routeData.policies),i=mc(e.route,n.routeData.policies);return Oi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Si({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Oi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Si,"createInternalPolicyProcessor");async function Oi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Or(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=gc(r),p;return E.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?p=l(c,t,e):p=c.ok?l(c,t,e):c,p}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Oi,"executePolicyProcessor");function Ci(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||fc,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]=hc(l,o)}i=u+1}return n}s(Ci,"parse");function fc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(fc,"decode");function hc(t,e){try{return e(t)}catch{return t}}s(hc,"tryDecode");function Ai(t,e){try{let n=/v\d+(-\d+)?/g,o=Ci(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Ai,"devPortalBaseURL");var Li="/__zuplo/dev-portal",yc="dev-portal-id",bc="dev-portal-host",wc="zp-account",Rc="zp-project",Pc="dev-portal-build",Ec=`
|
|
39
39
|
<!DOCTYPE html>
|
|
40
40
|
<html lang="en">
|
|
41
41
|
<head>
|
|
@@ -49,18 +49,18 @@
|
|
|
49
49
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
50
50
|
</body>
|
|
51
51
|
</html>
|
|
52
|
-
`,_i=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=E.instance.deploymentName,o=E.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(E.instance.isLocalDevelopment)return new Response(Ec,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let p=new URL(c.url),d=Ai(o,c.headers),m=new URL(`${p.pathname}${p.search}`,d),{headers:g,method:I,body:R}=c;return E.instance.build.ACCOUNT_NAME&&g.set(wc,E.instance.build.ACCOUNT_NAME),E.instance.build.PROJECT_NAME&&g.set(Rc,E.instance.build.PROJECT_NAME),g.set(yc,r),g.set(bc,p.host),g.set(Pc,E.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:I,body:R,redirect:"manual"})},"devPortalRoute"),a=new G({processors:[te,
|
|
52
|
+
`,_i=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=E.instance.deploymentName,o=E.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(E.instance.isLocalDevelopment)return new Response(Ec,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let p=new URL(c.url),d=Ai(o,c.headers),m=new URL(`${p.pathname}${p.search}`,d),{headers:g,method:I,body:R}=c;return E.instance.build.ACCOUNT_NAME&&g.set(wc,E.instance.build.ACCOUNT_NAME),E.instance.build.PROJECT_NAME&&g.set(Rc,E.instance.build.PROJECT_NAME),g.set(yc,r),g.set(bc,p.host),g.set(Pc,E.instance.build.BUILD_ID),await fetch(m.toString(),{headers:g,method:I,body:R,redirect:"manual"})},"devPortalRoute"),a=new G({processors:[te,Kt],handler:i,gateway:e}),u=new V({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"),ki=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(Li.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new G({processors:[te],handler:r,gateway:e}),i=new V({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Li}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var $i=_e(De());var yt="system-logger",Di="api-key";var Cr=0,bt=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){Cr>=Number.MAX_SAFE_INTEGER&&(Cr=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:Cr++};this.#t[e](u,a)}};var W=class extends Ne{static{s(this,"LogPlugin")}};var Yt=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 wt=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 Ic=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),xc=new Map(Ic);var vc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ar=Symbol(".toJSON was called"),Tc=s(t=>{t[Ar]=!0;let e=t.toJSON();return delete t[Ar],e},"toJSON"),Sc=s(t=>xc.get(t)??Error,"getErrorConstructor"),Ni=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&&ft(t)){let l=Sc(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[Ar]!==!0)return Tc(t);let c=s(l=>Ni({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,p]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(p)){n[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){n[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){n[l]=p;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:p}of vc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ft(t[l])?c(t[l]):t[l],enumerable:r?!0:p,configurable:!0,writable:!0});return n},"destroyCircular");function oe(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Ni({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(oe,"serializeError");var Oc=/file:\/\/\/(.*?)\/dist\//g,Cc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Ac="at async Event.respondWith";function Mi(t){return typeof t!="string"?t:t.split(`
|
|
53
53
|
`).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Oc,"").replaceAll(Cc,"").replaceAll(Ac,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
54
54
|
`)}s(Mi,"cleanStack");function Qt(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let p=u.indent||" ",d;u.inlineCharacterLimit===void 0?d={newline:`
|
|
55
55
|
`,newlineOrSpace:`
|
|
56
56
|
`,pad:c,indent:c+p}:d={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(d.newline,"g"),"").replace(new RegExp(d.newlineOrSpace,"g")," ").replace(new RegExp(d.pad+"|"+d.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(d.newline+"|"+d.newlineOrSpace,"g"),`
|
|
57
57
|
`).replace(new RegExp(d.pad,"g"),c).replace(new RegExp(d.indent,"g"),c+p)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||bi(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let g="["+d.newline+a.map((I,R)=>{let v=a.length-1===R?d.newline:","+d.newlineOrSpace,k=i(I,u,c+p,l+1);return u.transform&&(k=u.transform(a,R,k)),d.indent+k+v}).join("")+d.pad+"]";return r.pop(),m(g)}if(Me(a)){let g=wi(a);if(u.filter&&(g=g.filter(R=>u.filter?.(a,R))),g.length===0)return"{}";r.push(a);let I="{"+d.newline+g.map((R,v)=>{let k=g.length-1===v?d.newline:","+d.newlineOrSpace,f=typeof R=="symbol",P=!f&&/^[a-z$_][$\w]*$/i.test(R),A=f||P?R:i(R,u,"",l+1),Z=i(a[R],u,c+p,l+1);return u.transform&&(Z=u.transform(a,R,Z)),d.indent+String(A)+": "+Z+k}).join("")+d.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
|
|
58
58
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(Qt,"stringifyObject");function Oe(t){return t.map(e=>oe(e))}s(Oe,"makeErrorsSerializable");function We(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:Pe(oe(e))}s(We,"extractBestMessage");function Ui(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ft(n))if(n.stack)e.push(n.stack);else{let r=Qt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Qt(n);e.push(r)}else{let r=Lr(n);e.push(r)}}),e.join(`
|
|
59
|
-
`)}s(Ui,"messagesToMultilineText");function Pe(t){return typeof t=="string"?t:JSON.stringify(t)}s(Pe,"stringifyNonString");function Lr(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"?yr(t):"unknown"}s(Lr,"stringifyNonStringToText");var Xt=require("jose");async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let 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 h("An unknown error occurred, ensure retries is not negative")}s(ie,"fetchRetry");async function ye({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Xt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ye,"getTokenFromGcpServiceAccount");async function Hi(t,e,n){return Zi(t,{token:e,returnSecureToken:!0},n)}s(Hi,"exchangeFirebaseJwtForIdToken");async function en(t,e,n){return Zi(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(en,"exchangeGgpJwtForIdToken");async function Zi(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new C({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Zi,"fetchToken");var ae=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,Xt.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 tn=class extends W{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Rt(this.options)}},Lc="https://logging.googleapis.com/v2/entries:write?alt=json",_r={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Rt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=E.instance.loggingEnvironmentType,this.#i=E.instance.loggingEnvironmentStage,this.#r=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ae.init(this.#e)}log(e,n){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Oe(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_r[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=We(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 ae.init(this.#e));let n=await ye({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Lc,{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 B("google-log-transport",1,this.dispatchFunction)};var nn="gcp";function rn(t){let e={allMessages:Oe(t.messages)},n="zuplo-production",r=We(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:_r[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(rn,"gcpLogFormat");var Pt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(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 on=class extends W{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Et(this.options)}},kr="__ddtags",Dr="__ddattr",Nr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),_c=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Nr(r)):n.push(`${Nr(r)}:${Nr(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=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[kr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[kr]!==void 0);a>-1&&(Object.assign(r,i[a][kr]),i.splice(a,1));let u={},c=n.custom[Dr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Dr]!==void 0);l>-1&&(Object.assign(u,i[l][Dr]),i.splice(l,1));let p=Oe(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:p},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:We(p),service:e.loggingId,ddtags:_c(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new B("data-dog-transport",10,this.dispatchFunction)};var It=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(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 kc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:Oe(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{s(this,"RemoteLogTransport")}constructor(e){sn||(sn=new B("remote-log-transport",1,kc(e)))}log(e,n){sn.enqueue(e),n.waitUntil(sn.waitUntilFlushed())}};var Dc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},qi=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:Dc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Nc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=qi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{s(this,"UnifiedLogTransport")}constructor(e){un||(un=new B("unified-log-transport",1,Nc(e)))}async log(e,n){un.enqueue(e),n.waitUntil(un.waitUntilFlushed())}};var Mr=(0,$i.debug)("zuplo:logging"),ln=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(E.instance,e),r=await t.setupUserCoreLogger(E.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Mr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(yt);return i?o.push(new It(i.logger,e.logFormat)):e.isDeno&&o.push(new Pt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new cn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new bt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Mr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(yt);if(a&&a.captureUserLogs===!0?r.push(new It(a.logger,e.logFormat)):e.isDeno&&r.push(new Pt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new an({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Rt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Et({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof W&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new bt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Mr("Gateway.createRequestLoggers");let a=new Yt(r,o,i),u=new wt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new wt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var qe=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 Ur=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},Ke=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Hr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Je=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof qe||e instanceof V))throw new $("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 Ur(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Hr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new h(`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 Ke(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 Ke(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var be=(0,Fi.debug)("zuplo:runtime"),Mc=s(t=>{let e=t.findIndex(n=>n.name===gt.name);return e>-1?[...t.splice(e),gt]:[...t,gt]},"setupSystemNoVersion"),Y=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;be("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(be("Gateway.initialize"),!t.#e){await hi(i);let a=await ln.init(r),u=e(),c={...u,corsPolicies:Ii(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){be("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new $("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Jt,Wt,te];#o;setupRoutes=()=>{be("Gateway.setupRoutes");let e=this.routeData,n=Mc(e.versions),r=new Je(n);if(e.routes.length===0)return fr(r,this),Ir(r,this),Pr(r,this),xi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ki(r,this),_i(r,this)),fr(r,this),Ir(r,this),Pr(r,this);for(let i of Te)i instanceof Re&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new h(`Invalid state - No handler on route for path '${i.path}'`);let u=new G({processors:this.#r,handler:a,gateway:this}),c=new qe(i);r.addRoute(c,u.execute)}),vi(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 h("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 be("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){be("Gateway.internalErrorResponse");let o={};if(E.instance.isDeno){if(r instanceof C&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=oe(r.cause);"stack"in i&&(i.stack=Mi(i.stack)),o={cause:i}}}return T.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return jo.forEach(r=>{n.delete(r)}),E.instance.isDeno&&zo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ut)??e.headers.get(Mo),o=e.headers.get(je);if(!r){r=crypto.randomUUID();let v=new Headers(e.headers);v.set(ut,r),e=new Request(e,{headers:v})}if(["GET","HEAD"].includes(e.method)&&e.body){let v=new Headers(e.headers);v.set(Uo,"true"),e=new Request(e,{headers:v,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,p=this.#n.lookup(e.method,l);if(!p)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let d=new dn(e.headers),m=this.#s(e),g=new z(m,{params:p.params}),I=new pn({logger:a,route:p.routeConfiguration,requestId:r,event:n,custom:i,incomingRequestProperties:d}),R=ee.initialize(I,g);if(p.routeConfiguration===Er&&pt.value?.notFoundHandler!==void 0){let v=this.#n.lookupByPathOnly(l);R.pathOnlyMatches=v.map(k=>k.routeConfiguration).filter(k=>k instanceof qe)}try{if(F.addLogger(I,u),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(c):!c.pathname.startsWith("/__zuplo")){let f=await mi(g,I);if(f instanceof Response)return f;{let P=ee.getContextExtensions(I);g=f,P.latestRequest=g}}mt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:p.routeConfiguration.path});let v=p.executableHandler;Uc(v,p,e),be("Gateway.handleRequest - call user handler");let k=await v(g,I);if(be("Gateway.handleRequest - user handler"),!(k instanceof Response))throw new C(`Invalid Response type from the request handler: ${typeof k}`);if(k.bodyUsed)throw new C("The response object has already been used. Return a new response instead.");if(k.headers.get(ut)===null&&!k.webSocket){let f=new Headers(k.headers);return f.set(ut,r),new Response(k.body,{status:k.status,statusText:k.statusText,headers:f,cf:k.cf})}else return k}catch(v){return be("Gateway - error executing handler",v),v instanceof C?(a.error(v),u.warn(v)):u.error(v),await this.#i(g,I,v)}}};function Uc(t,e,n){if(be("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new h(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new h(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Uc,"checkHandler");var Bi=s(async(t,e,n)=>{let r=Y.instance.routeData.policies,o=ht([t],r);if(o.length===0)throw new C(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var dn=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(er)??void 0}get city(){return this.#e.get(Wn)??this.#e.get(Ho)??void 0}get continent(){return this.#e.get(Kn)??this.#e.get(Zo)??void 0}get country(){return this.#e.get(Jn)??this.#e.get(qo)??void 0}get latitude(){return this.#e.get(Qn)??this.#e.get(Fo)??void 0}get longitude(){return this.#e.get(Yn)??this.#e.get($o)??void 0}get colo(){return this.#e.get(tr)??void 0}get postalCode(){return this.#e.get(nr)??void 0}get metroCode(){return this.#e.get(rr)??void 0}get region(){return this.#e.get(or)??void 0}get regionCode(){return this.#e.get(ir)??void 0}get timezone(){return this.#e.get(sr)??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}}},ze=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ve=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},ee=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 C(`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}},pn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event: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)=>Bi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ee.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;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 le=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),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Hc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Zr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Hc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(Zr,"isRestrictedEnvVariableName");function qr(t){return!!t.startsWith("ZUPLO_")}s(qr,"isZuploReadableEnvVariableName");var ne=new Proxy({},{get(t,e){if(Zr(String(e))&&!qr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var zi=_e(De());var pe=(0,zi.debug)("zuplo:runtime:external-service");function Vi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=E.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Vi,"getServiceAuth");async function Gi(t){let e=Vi();if(!e)throw pe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.");if(typeof t!="string")throw pe("Cannot call external service with Request object"),new C("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(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Ki(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Gi,"externalServiceTunnelConfig");async function Wi(t,e){let n=Vi();if(n)if(pe(`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(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let p=E.instance.build;if(p.ACCOUNT_NAME&&p.PROJECT_NAME&&p.ENVIRONMENT_TYPE)u=`https://${await Ki(o,p.ACCOUNT_NAME,p.PROJECT_NAME,p.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);pe(`Calling external service: ${c.toString()}`);let l=await Ye(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 C("Could not connect to secure tunnel.");return l}else throw pe("Cannot call external service with Request object"),new C("Currently, we only support fetch(<some_string>, ...).");else throw pe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.")}s(Wi,"externalServiceHandler");async function Ki(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Zc(r);pe(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await ji(`${i}-${o}`),l=await ji(`${i}-${a}-${u}`);return`${c}.${l}`}s(Ki,"hashServiceName");async function ji(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(ji,"hashSegment");function Zc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Zc,"sanitizeEnvironmentType");var Ji=new Map;Ji.set("service:",Wi);var Ye=globalThis.fetch;globalThis.fetch=function(t,e){let n=qc(e);if(typeof t=="string"){let r=new URL(t),o=Ji.get(r.protocol);return o?o(t,n):Ye(t,n)}else return Ye(t,n)};var qc=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 Yi=s(()=>{Y.purgeGatewayCache()},"purgeGatewayCache"),mn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=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)=>{E.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Y.initialize(this.routeLoader,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 h&&(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:E.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 ss=_e(De());function $c(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($c,"lexer");function $r(t,e){e===void 0&&(e={});for(var n=$c(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Bc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",p=s(function(y){if(c<n.length&&n[c].type===y)return n[c++].value},"tryConsume"),d=s(function(y){var w=p(y);if(w!==void 0)return w;var S=n[c],N=S.type,O=S.index;throw new TypeError("Unexpected ".concat(N," at ").concat(O,", expected ").concat(y))},"mustConsume"),m=s(function(){for(var y="",w;w=p("CHAR")||p("ESCAPED_CHAR");)y+=w;return y},"consumeText");c<n.length;){var g=p("CHAR"),I=p("NAME"),R=p("PATTERN");if(I||R){var v=g||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:v,suffix:"",pattern:R||i,modifier:p("MODIFIER")||""});continue}var k=g||p("ESCAPED_CHAR");if(k){l+=k;continue}l&&(a.push(l),l="");var f=p("OPEN");if(f){var v=m(),P=p("NAME")||"",A=p("PATTERN")||"",Z=m();d("CLOSE"),a.push({name:P||(A?u++:""),pattern:P&&!A?i:A,prefix:v,suffix:Z,modifier:p("MODIFIER")||""});continue}d("END")}return a}s($r,"parse");function Qi(t,e){return Fc($r(t,e),e)}s(Qi,"compile");function Fc(t,e){e===void 0&&(e={});var n=jc(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="",p=0;p<t.length;p++){var d=t[p];if(typeof d=="string"){l+=d;continue}var m=c?c[d.name]:void 0,g=d.modifier==="?"||d.modifier==="*",I=d.modifier==="*"||d.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(d.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(d.name,'" to not be empty'))}for(var R=0;R<m.length;R++){var v=o(m[R],d);if(a&&!u[p].test(v))throw new TypeError('Expected all "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix}continue}if(typeof m=="string"||typeof m=="number"){var v=o(String(m),d);if(a&&!u[p].test(v))throw new TypeError('Expected "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix;continue}if(!g){var k=I?"an array":"a string";throw new TypeError('Expected "'.concat(d.name,'" to be ').concat(k))}}return l}}s(Fc,"tokensToFunction");function Bc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Bc,"escapeString");function jc(t){return t&&t.sensitive?"":"i"}s(jc,"flags");var ns=_e(De());var zc=(0,ns.debug)("zuplo:runtime"),Br=new TextEncoder,Xi={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"},Vc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Qe=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 jr(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){zc("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 h("An unknown error occurred, ensure retries is not negative")}},jr=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:p,datetime:d,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:R}){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 v,k;(!c||!l)&&([v,k]=Gc(this.url,this.headers)),this.service=c||v||"",this.region=l||k||"us-east-1",this.cache=p||new Map,this.datetime=d||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let f=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),f.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&f.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>I||!Vc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
|
|
59
|
+
`)}s(Ui,"messagesToMultilineText");function Pe(t){return typeof t=="string"?t:JSON.stringify(t)}s(Pe,"stringifyNonString");function Lr(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"?yr(t):"unknown"}s(Lr,"stringifyNonStringToText");var Xt=require("jose");async function ie(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let 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 h("An unknown error occurred, ensure retries is not negative")}s(ie,"fetchRetry");async function ye({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Xt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ye,"getTokenFromGcpServiceAccount");async function Hi(t,e,n){return Zi(t,{token:e,returnSecureToken:!0},n)}s(Hi,"exchangeFirebaseJwtForIdToken");async function en(t,e,n){return Zi(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(en,"exchangeGgpJwtForIdToken");async function Zi(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new C({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Zi,"fetchToken");var ae=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,Xt.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 tn=class extends W{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Rt(this.options)}},Lc="https://logging.googleapis.com/v2/entries:write?alt=json",_r={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Rt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=E.instance.loggingEnvironmentType,this.#i=E.instance.loggingEnvironmentStage,this.#r=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ae.init(this.#e)}log(e,n){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Oe(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_r[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=We(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 ae.init(this.#e));let n=await ye({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Lc,{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 B("google-log-transport",1,this.dispatchFunction)};var nn="gcp";function rn(t){let e={allMessages:Oe(t.messages)},n="zuplo-production",r=We(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:_r[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(rn,"gcpLogFormat");var Pt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(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 on=class extends W{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Et(this.options)}},kr="__ddtags",Dr="__ddattr",Nr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),_c=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Nr(r)):n.push(`${Nr(r)}:${Nr(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=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[kr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[kr]!==void 0);a>-1&&(Object.assign(r,i[a][kr]),i.splice(a,1));let u={},c=n.custom[Dr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Dr]!==void 0);l>-1&&(Object.assign(u,i[l][Dr]),i.splice(l,1));let p=Oe(i),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:p},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:We(p),service:e.loggingId,ddtags:_c(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new B("data-dog-transport",10,this.dispatchFunction)};var It=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(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 kc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:Oe(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{s(this,"RemoteLogTransport")}constructor(e){sn||(sn=new B("remote-log-transport",1,kc(e)))}log(e,n){sn.enqueue(e),n.waitUntil(sn.waitUntilFlushed())}};var Dc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},qi=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:Dc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Nc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=qi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":E.instance.systemUserAgent,"zp-dn":E.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{s(this,"UnifiedLogTransport")}constructor(e){un||(un=new B("unified-log-transport",1,Nc(e)))}async log(e,n){un.enqueue(e),n.waitUntil(un.waitUntilFlushed())}};var Mr=(0,$i.debug)("zuplo:logging"),ln=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(E.instance,e),r=await t.setupUserCoreLogger(E.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Mr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(yt);return i?o.push(new It(i.logger,e.logFormat)):e.isDeno&&o.push(new Pt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new cn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new bt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Mr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(yt);if(a&&a.captureUserLogs===!0?r.push(new It(a.logger,e.logFormat)):e.isDeno&&r.push(new Pt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new an({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Rt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Et({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Te.forEach(u=>{u instanceof W&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new bt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Mr("Gateway.createRequestLoggers");let a=new Yt(r,o,i),u=new wt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new wt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var qe=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 Ur=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},Je=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Hr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof qe||e instanceof V))throw new $("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 Ur(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Hr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new h(`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 Je(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 Je(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var be=(0,Fi.debug)("zuplo:runtime"),Mc=s(t=>{let e=t.findIndex(n=>n.name===gt.name);return e>-1?[...t.splice(e),gt]:[...t,gt]},"setupSystemNoVersion"),Y=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;be("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(be("Gateway.initialize"),!t.#e){await hi(i);let a=await ln.init(r),u=e(),c={...u,corsPolicies:Ii(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){be("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new $("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Kt,Wt,te];#o;setupRoutes=()=>{be("Gateway.setupRoutes");let e=this.routeData,n=Mc(e.versions),r=new Ke(n);if(e.routes.length===0)return fr(r,this),Ir(r,this),Pr(r,this),xi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ki(r,this),_i(r,this)),fr(r,this),Ir(r,this),Pr(r,this);for(let i of Te)i instanceof Re&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new h(`Invalid state - No handler on route for path '${i.path}'`);let u=new G({processors:this.#r,handler:a,gateway:this}),c=new qe(i);r.addRoute(c,u.execute)}),vi(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 h("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 be("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){be("Gateway.internalErrorResponse");let o={};if(E.instance.isDeno){if(r instanceof C&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=oe(r.cause);"stack"in i&&(i.stack=Mi(i.stack)),o={cause:i}}}return T.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return jo.forEach(r=>{n.delete(r)}),E.instance.isDeno&&zo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ut)??e.headers.get(Mo),o=e.headers.get(je);if(!r){r=crypto.randomUUID();let v=new Headers(e.headers);v.set(ut,r),e=new Request(e,{headers:v})}if(["GET","HEAD"].includes(e.method)&&e.body){let v=new Headers(e.headers);v.set(Uo,"true"),e=new Request(e,{headers:v,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,p=this.#n.lookup(e.method,l);if(!p)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let d=new dn(e.headers),m=this.#s(e),g=new z(m,{params:p.params}),I=new pn({logger:a,route:p.routeConfiguration,requestId:r,event:n,custom:i,incomingRequestProperties:d}),R=ee.initialize(I,g);if(p.routeConfiguration===Er&&pt.value?.notFoundHandler!==void 0){let v=this.#n.lookupByPathOnly(l);R.pathOnlyMatches=v.map(k=>k.routeConfiguration).filter(k=>k instanceof qe)}try{if(F.addLogger(I,u),E.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(c):!c.pathname.startsWith("/__zuplo")){let f=await mi(g,I);if(f instanceof Response)return f;{let P=ee.getContextExtensions(I);g=f,P.latestRequest=g}}mt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:p.routeConfiguration.path});let v=p.executableHandler;Uc(v,p,e),be("Gateway.handleRequest - call user handler");let k=await v(g,I);if(be("Gateway.handleRequest - user handler"),!(k instanceof Response))throw new C(`Invalid Response type from the request handler: ${typeof k}`);if(k.bodyUsed)throw new C("The response object has already been used. Return a new response instead.");if(k.headers.get(ut)===null&&!k.webSocket){let f=new Headers(k.headers);return f.set(ut,r),new Response(k.body,{status:k.status,statusText:k.statusText,headers:f,cf:k.cf})}else return k}catch(v){return be("Gateway - error executing handler",v),v instanceof C?(a.error(v),u.warn(v)):u.error(v),await this.#i(g,I,v)}}};function Uc(t,e,n){if(be("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new h(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new h(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Uc,"checkHandler");var Bi=s(async(t,e,n)=>{let r=Y.instance.routeData.policies,o=ht([t],r);if(o.length===0)throw new C(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var dn=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(er)??void 0}get city(){return this.#e.get(Wn)??this.#e.get(Ho)??void 0}get continent(){return this.#e.get(Jn)??this.#e.get(Zo)??void 0}get country(){return this.#e.get(Kn)??this.#e.get(qo)??void 0}get latitude(){return this.#e.get(Qn)??this.#e.get(Fo)??void 0}get longitude(){return this.#e.get(Yn)??this.#e.get($o)??void 0}get colo(){return this.#e.get(tr)??void 0}get postalCode(){return this.#e.get(nr)??void 0}get metroCode(){return this.#e.get(rr)??void 0}get region(){return this.#e.get(or)??void 0}get regionCode(){return this.#e.get(ir)??void 0}get timezone(){return this.#e.get(sr)??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}}},ze=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ve=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},ee=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 C(`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}},pn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event: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)=>Bi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ee.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;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 le=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),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Hc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Zr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Hc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(Zr,"isRestrictedEnvVariableName");function qr(t){return!!t.startsWith("ZUPLO_")}s(qr,"isZuploReadableEnvVariableName");var ne=new Proxy({},{get(t,e){if(Zr(String(e))&&!qr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var zi=_e(De());var pe=(0,zi.debug)("zuplo:runtime:external-service");function Vi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=E.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Vi,"getServiceAuth");async function Gi(t){let e=Vi();if(!e)throw pe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.");if(typeof t!="string")throw pe("Cannot call external service with Request object"),new C("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(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let a=E.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Ji(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Gi,"externalServiceTunnelConfig");async function Wi(t,e){let n=Vi();if(n)if(pe(`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(E.instance.useSha256ServiceRouting){pe("Using sha256 service routing");let p=E.instance.build;if(p.ACCOUNT_NAME&&p.PROJECT_NAME&&p.ENVIRONMENT_TYPE)u=`https://${await Ji(o,p.ACCOUNT_NAME,p.PROJECT_NAME,p.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw pe("Cannot use sha256 service routing, missing build variables"),new C("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);pe(`Calling external service: ${c.toString()}`);let l=await Ye(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 C("Could not connect to secure tunnel.");return l}else throw pe("Cannot call external service with Request object"),new C("Currently, we only support fetch(<some_string>, ...).");else throw pe("There is no external service auth configured for this zup."),new C("There are no external services configured for this zup.")}s(Wi,"externalServiceHandler");async function Ji(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Zc(r);pe(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await ji(`${i}-${o}`),l=await ji(`${i}-${a}-${u}`);return`${c}.${l}`}s(Ji,"hashServiceName");async function ji(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(ji,"hashSegment");function Zc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Zc,"sanitizeEnvironmentType");var Ki=new Map;Ki.set("service:",Wi);var Ye=globalThis.fetch;globalThis.fetch=function(t,e){let n=qc(e);if(typeof t=="string"){let r=new URL(t),o=Ki.get(r.protocol);return o?o(t,n):Ye(t,n)}else return Ye(t,n)};var qc=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 Yi=s(()=>{Y.purgeGatewayCache()},"purgeGatewayCache"),mn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=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)=>{E.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Y.initialize(this.routeLoader,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 h&&(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:E.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 ss=_e(De());function $c(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($c,"lexer");function $r(t,e){e===void 0&&(e={});for(var n=$c(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Bc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",p=s(function(y){if(c<n.length&&n[c].type===y)return n[c++].value},"tryConsume"),d=s(function(y){var w=p(y);if(w!==void 0)return w;var S=n[c],N=S.type,O=S.index;throw new TypeError("Unexpected ".concat(N," at ").concat(O,", expected ").concat(y))},"mustConsume"),m=s(function(){for(var y="",w;w=p("CHAR")||p("ESCAPED_CHAR");)y+=w;return y},"consumeText");c<n.length;){var g=p("CHAR"),I=p("NAME"),R=p("PATTERN");if(I||R){var v=g||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:v,suffix:"",pattern:R||i,modifier:p("MODIFIER")||""});continue}var k=g||p("ESCAPED_CHAR");if(k){l+=k;continue}l&&(a.push(l),l="");var f=p("OPEN");if(f){var v=m(),P=p("NAME")||"",A=p("PATTERN")||"",Z=m();d("CLOSE"),a.push({name:P||(A?u++:""),pattern:P&&!A?i:A,prefix:v,suffix:Z,modifier:p("MODIFIER")||""});continue}d("END")}return a}s($r,"parse");function Qi(t,e){return Fc($r(t,e),e)}s(Qi,"compile");function Fc(t,e){e===void 0&&(e={});var n=jc(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="",p=0;p<t.length;p++){var d=t[p];if(typeof d=="string"){l+=d;continue}var m=c?c[d.name]:void 0,g=d.modifier==="?"||d.modifier==="*",I=d.modifier==="*"||d.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(d.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(d.name,'" to not be empty'))}for(var R=0;R<m.length;R++){var v=o(m[R],d);if(a&&!u[p].test(v))throw new TypeError('Expected all "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix}continue}if(typeof m=="string"||typeof m=="number"){var v=o(String(m),d);if(a&&!u[p].test(v))throw new TypeError('Expected "'.concat(d.name,'" to match "').concat(d.pattern,'", but got "').concat(v,'"'));l+=d.prefix+v+d.suffix;continue}if(!g){var k=I?"an array":"a string";throw new TypeError('Expected "'.concat(d.name,'" to be ').concat(k))}}return l}}s(Fc,"tokensToFunction");function Bc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Bc,"escapeString");function jc(t){return t&&t.sensitive?"":"i"}s(jc,"flags");var ns=_e(De());var zc=(0,ns.debug)("zuplo:runtime"),Br=new TextEncoder,Xi={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"},Vc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Qe=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 jr(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){zc("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 h("An unknown error occurred, ensure retries is not negative")}},jr=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:p,datetime:d,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:R}){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 v,k;(!c||!l)&&([v,k]=Gc(this.url,this.headers)),this.service=c||v||"",this.region=l||k||"us-east-1",this.cache=p||new Map,this.datetime=d||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let f=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),f.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&f.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>I||!Vc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
|
|
60
60
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!f.has("X-Amz-Expires")&&f.set("X-Amz-Expires","86400"),f.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),f.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ts(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(P.has(A))return!1;P.add(A)}return!0}).map(A=>A.map(Z=>ts(encodeURIComponent(Z)))).sort(([A,Z],[y,w])=>A<y?-1:A>y?1:Z<w?-1:Z>w?1:0).map(A=>A.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 xt("AWS4"+this.secretAccessKey,e),i=await xt(o,this.region),a=await xt(i,this.service);r=await xt(a,"aws4_request"),this.cache.set(n,r)}return Fr(await xt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fr(await es(await this.canonicalString()))].join(`
|
|
61
61
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
62
62
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
63
|
-
`)}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 C("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fr(await es(this.body||""))}return e}};async function xt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Br.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Br.encode(e))}s(xt,"hmac");async function es(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Br.encode(t):t)}s(es,"hash");function Fr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Fr,"buf2hex");function ts(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ts,"encodeRfc3986");function Gc(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 Xi?[Xi[i],a]:[i,a]}s(Gc,"guessServiceRegion");function Wc(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(Wc,"b64ToUint6");function rs(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 p=0;p<r;p++)if(u=p&3,c|=Wc(n.charCodeAt(p))<<6*(3-u),u===3||r-p===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(rs,"base64Decode");function gn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(gn,"uint6ToB64");function os(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(gn(o>>>18&63),gn(o>>>12&63),gn(o>>>6&63),gn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(os,"base64Encode");function Xe(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Xe,"numberToString");function Kc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Xe(Math.floor(n/60)),i=Xe(n%60);return`${r}${o}${i}`}s(Kc,"getCLFOffset");function zr(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=Xe(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Xe(t.getHours()),a=Xe(t.getMinutes()),u=Xe(t.getSeconds()),c=Kc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(zr,"toCLFDate");var is=(0,ss.debug)("zuplo:runtime"),Jc="X-Amzn-Trace-Id",Yc="x-amzn-errortype",as=[],Qc=s(async(t,e,n)=>{let r=n;for await(let o of as)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ue=class extends C{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Jc)??void 0,this.errorType=n.get(Yc)??void 0}},us={addSendingAwsLambdaEventHook:t=>{as.push(t)}};async function cs(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 h("awsAccessKeyId is not set in the handler options");if(!r)throw new h("secretAccessKey is not set in the handler options");if(!o)throw new h("region is not set in the handler options");if(!i)throw new h("functionName is not set in the handler options");let l=new Qe({accessKeyId:n,secretAccessKey:r}),p=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(is(`AWS Lambda URL: ${p}`),!a)return l.fetch(p,{body:await t.arrayBuffer()});let[d,m]=await nl(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=tl(t,e):I=await el(t,e,{useAwsResourcePathStyle:u}),is("Calling onSendingAwsLambdaEvent hook");let R=await Qc(t,e,I);R.body=d,R.isBase64Encoded=m;let v=await l.fetch(p,{body:JSON.stringify(R)});try{return Xc(v)}catch(k){if(k instanceof ue){let f=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&k.traceId?{AMZN_TRACE_ID_HEADER:k.traceId}:void 0;return T.internalServerError(t,e,void 0,f)}throw k}}s(cs,"awsLambdaHandler");async function Xc(t){let e;try{e=await t.json()}catch{throw new ue("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 ue(e.message,t.headers):new ue(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ue(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 ue(`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 ue(`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 ue(`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 ue("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ue("Response was set to base64 encoded but body was not a string",t.headers);r=rs(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 ue(`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(Xc,"getResponse");async function el(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,p)=>{r[p]=l,o[p]=[l]});let i=t.query,a={};for(let[l,p]of Object.entries(i))a[l]=[p];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:zr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ol(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(el,"buildEventVersion1");function tl(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:zr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(tl,"buildEventVersion2");async function nl(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&&rl(e,o)){let i=await t.arrayBuffer();n=os(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(nl,"getBodyResult");function rl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(rl,"matchesContentType");function ol(t,e=!1){if(!e)return t;let n=$r(t),r=Qi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(ol,"getResourcePath");var il=[502,503,504];async function et(t,e){if(il.includes(t.status)){let n=F.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(et,"logBadGatewayResponses");var Vr;function Ce(t){if(Vr===void 0){let n=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Vr=n}return t.log[Vr]}s(Ce,"getHandlerUserLogFunction");async function ls(t,e){let n=E.instance.build.BUILD_ID,{buildAssetsUrl:r}=E.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new h("Open API Spec Handler must have 'openApiFilePath' specified");let a=sl(i);if(!a.isValid)throw new h(a.error);let u;E.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 T.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return et(l,e),l}s(ls,"openApiSpecHandler");var sl=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 ds(t,e){let n=e.route.handler.options;if(!n.location)throw new h("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(ds,"redirectHandler");function al(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(al,"join");async function ps(t,e){let n=Ce(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 h("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=al(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),p=Date.now();n(`URL Forwarding to '${l}'`);let d=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-p;return n(`URL Forward received response ${d.status} - ${d.statusText} in ${m}ms`),et(d,e),d}s(ps,"urlForwardHandler");var ul=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 ms(t,e){let n=Ce(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new h("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?ul(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let p=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),d=Date.now()-l;return n(`URL Rewrite received response ${p.status} - ${p.statusText} in ${d}ms`),et(p,e),p}s(ms,"urlRewriteHandler");async function gs(t,e){let n=E.instance,r=e.route.handler.options,o=Ce(e);if(!r||!r.rewritePattern)throw new h("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new h("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 d=new Headers(t.headers);if(u.startsWith("service:")){let g=await Gi(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let v in g.tunnelHeaders)d.set(v,g.tunnelHeaders[v])}u=u.replace(/^(http)/,"ws");try{if(d.get("Authorization")){let g=d.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:d})}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 d=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${d}'`;throw new Error(m)}let p=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${p}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(gs,"webSocketHandler");var Gr=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 h(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),fs=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 hs(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{let u=s(async c=>{let l=await fs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(hs,"wireUpListeners");async function ys(t,e){let n=E.instance,r=e.route.handler.options,o=Ce(e);if(!r||!r.rewritePattern)throw new h("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new h("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 h("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 k=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${k}'`;throw new Error(f)}let p=new WebSocketPair,[d,m]=Object.values(p),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let R=r.policies&&r.policies.inbound?Gr(r.policies.inbound,"inbound"):[],v=r.policies&&r.policies.outbound?Gr(r.policies.outbound,"outbound"):[];return hs(m,I,t,e,R),hs(I,m,t,e,v),new Response(null,{status:101,webSocket:d})}s(ys,"webSocketPipelineHandler");var fn=class extends W{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Wr(this.options)}},Wr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Pe(oe(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new B("dyna-trace-log-transport",10,this.#i)};var hn=class extends W{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Jr(this.options)}},Kr=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 cl(t,e){return btoa(`${t}:${e}`)}s(cl,"createBasicDigest");var Jr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=cl(e.username,e.password),this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Kr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:Pe(oe(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 B("loki-log-transport",10,this.#s)};var yn=class extends W{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=E.instance.loggingEnvironmentType,this.#r=E.instance.loggingEnvironmentStage,this.#t=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Pe(oe(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
63
|
+
`)}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 C("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fr(await es(this.body||""))}return e}};async function xt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Br.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Br.encode(e))}s(xt,"hmac");async function es(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Br.encode(t):t)}s(es,"hash");function Fr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Fr,"buf2hex");function ts(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ts,"encodeRfc3986");function Gc(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 Xi?[Xi[i],a]:[i,a]}s(Gc,"guessServiceRegion");function Wc(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(Wc,"b64ToUint6");function rs(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 p=0;p<r;p++)if(u=p&3,c|=Wc(n.charCodeAt(p))<<6*(3-u),u===3||r-p===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(rs,"base64Decode");function gn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(gn,"uint6ToB64");function os(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(gn(o>>>18&63),gn(o>>>12&63),gn(o>>>6&63),gn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(os,"base64Encode");function Xe(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Xe,"numberToString");function Jc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Xe(Math.floor(n/60)),i=Xe(n%60);return`${r}${o}${i}`}s(Jc,"getCLFOffset");function zr(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=Xe(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Xe(t.getHours()),a=Xe(t.getMinutes()),u=Xe(t.getSeconds()),c=Jc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(zr,"toCLFDate");var is=(0,ss.debug)("zuplo:runtime"),Kc="X-Amzn-Trace-Id",Yc="x-amzn-errortype",as=[],Qc=s(async(t,e,n)=>{let r=n;for await(let o of as)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ue=class extends C{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Kc)??void 0,this.errorType=n.get(Yc)??void 0}},us={addSendingAwsLambdaEventHook:t=>{as.push(t)}};async function cs(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 h("awsAccessKeyId is not set in the handler options");if(!r)throw new h("secretAccessKey is not set in the handler options");if(!o)throw new h("region is not set in the handler options");if(!i)throw new h("functionName is not set in the handler options");let l=new Qe({accessKeyId:n,secretAccessKey:r}),p=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(is(`AWS Lambda URL: ${p}`),!a)return l.fetch(p,{body:await t.arrayBuffer()});let[d,m]=await nl(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=tl(t,e):I=await el(t,e,{useAwsResourcePathStyle:u}),is("Calling onSendingAwsLambdaEvent hook");let R=await Qc(t,e,I);R.body=d,R.isBase64Encoded=m;let v=await l.fetch(p,{body:JSON.stringify(R)});try{return Xc(v)}catch(k){if(k instanceof ue){let f=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&k.traceId?{AMZN_TRACE_ID_HEADER:k.traceId}:void 0;return T.internalServerError(t,e,void 0,f)}throw k}}s(cs,"awsLambdaHandler");async function Xc(t){let e;try{e=await t.json()}catch{throw new ue("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 ue(e.message,t.headers):new ue(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ue(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 ue(`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 ue(`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 ue(`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 ue("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ue("Response was set to base64 encoded but body was not a string",t.headers);r=rs(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 ue(`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(Xc,"getResponse");async function el(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,p)=>{r[p]=l,o[p]=[l]});let i=t.query,a={};for(let[l,p]of Object.entries(i))a[l]=[p];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:zr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ol(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(el,"buildEventVersion1");function tl(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:zr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(tl,"buildEventVersion2");async function nl(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&&rl(e,o)){let i=await t.arrayBuffer();n=os(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(nl,"getBodyResult");function rl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(rl,"matchesContentType");function ol(t,e=!1){if(!e)return t;let n=$r(t),r=Qi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(ol,"getResourcePath");var il=[502,503,504];async function et(t,e){if(il.includes(t.status)){let n=F.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(et,"logBadGatewayResponses");var Vr;function Ce(t){if(Vr===void 0){let n=E.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Vr=n}return t.log[Vr]}s(Ce,"getHandlerUserLogFunction");async function ls(t,e){let n=E.instance.build.BUILD_ID,{buildAssetsUrl:r}=E.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new h("Open API Spec Handler must have 'openApiFilePath' specified");let a=sl(i);if(!a.isValid)throw new h(a.error);let u;E.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 T.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return et(l,e),l}s(ls,"openApiSpecHandler");var sl=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 ds(t,e){let n=e.route.handler.options;if(!n.location)throw new h("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(ds,"redirectHandler");function al(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(al,"join");async function ps(t,e){let n=Ce(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 h("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=al(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),p=Date.now();n(`URL Forwarding to '${l}'`);let d=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-p;return n(`URL Forward received response ${d.status} - ${d.statusText} in ${m}ms`),et(d,e),d}s(ps,"urlForwardHandler");var ul=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 ms(t,e){let n=Ce(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new h("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?ul(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let p=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),d=Date.now()-l;return n(`URL Rewrite received response ${p.status} - ${p.statusText} in ${d}ms`),et(p,e),p}s(ms,"urlRewriteHandler");async function gs(t,e){let n=E.instance,r=e.route.handler.options,o=Ce(e);if(!r||!r.rewritePattern)throw new h("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new h("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 d=new Headers(t.headers);if(u.startsWith("service:")){let g=await Gi(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let v in g.tunnelHeaders)d.set(v,g.tunnelHeaders[v])}u=u.replace(/^(http)/,"ws");try{if(d.get("Authorization")){let g=d.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:d})}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 d=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${d}'`;throw new Error(m)}let p=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${p}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(gs,"webSocketHandler");var Gr=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 h(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),fs=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 hs(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{let u=s(async c=>{let l=await fs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(hs,"wireUpListeners");async function ys(t,e){let n=E.instance,r=e.route.handler.options,o=Ce(e);if(!r||!r.rewritePattern)throw new h("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return T.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new h("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 h("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 k=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${k}'`;throw new Error(f)}let p=new WebSocketPair,[d,m]=Object.values(p),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let R=r.policies&&r.policies.inbound?Gr(r.policies.inbound,"inbound"):[],v=r.policies&&r.policies.outbound?Gr(r.policies.outbound,"outbound"):[];return hs(m,I,t,e,R),hs(I,m,t,e,v),new Response(null,{status:101,webSocket:d})}s(ys,"webSocketPipelineHandler");var fn=class extends W{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Wr(this.options)}},Wr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Pe(oe(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new B("dyna-trace-log-transport",10,this.#i)};var hn=class extends W{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Kr(this.options)}},Jr=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 cl(t,e){return btoa(`${t}:${e}`)}s(cl,"createBasicDigest");var Kr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=cl(e.username,e.password),this.#r=E.instance.loggingEnvironmentType,this.#o=E.instance.loggingEnvironmentStage,this.#n=E.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Jr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:Pe(oe(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 B("loki-log-transport",10,this.#s)};var yn=class extends W{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=E.instance.loggingEnvironmentType,this.#r=E.instance.loggingEnvironmentStage,this.#t=E.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Pe(oe(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
64
64
|
`),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 B("sumo-logic-log-transport",10,this.#s)};var ll="d3a5b78f-8236-48f5-b1df-4fe269d41172",bn=class extends W{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Qr(this.options)}},Qr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new h(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=E.instance.loggingEnvironmentType,this.#r=E.instance.loggingEnvironmentStage,this.#t=E.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;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Ui(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=Lr(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/${ll}`,{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 B("vmware-log-insights-log-transport",10,this.#s)};var wn=class extends W{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new B("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 Qe({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=E.instance.loggingEnvironmentType,this.environment=E.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Pe(oe(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var eo=new WeakMap,dl={tags:[]},Rn=class extends Se{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new to(this.options)}static setContext(n,r){let o=eo.get(n);o||(o=dl);let i=Object.assign({...o},r);eo.set(n,i)}},to=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 B("data-dog-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(eo.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 no(await r.text())}},no=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var ro=new WeakMap,pl={dimensions:[]},Pn=class extends Se{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new oo(this.options)}static setContext(n,r){let o=ro.get(n);o||(o=pl);let i=Object.assign({...o},r);ro.set(n,i)}},oo=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 B("dynatrace-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(ro.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(`
|
|
65
65
|
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new io(await r.text())}},io=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var En=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 In=class extends Re{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new so(e,this.#e,this.#t)}},bs=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),ml={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},so=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...ml};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 B("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?bs(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?bs(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(),p=u.clone(),d=this.#o(p,a,n,o,l-i,c.user?.sub).catch(m=>{n.log.error(m)});n.waitUntil(d)}),e}catch(r){return n.log.error(r),e}}};var ao=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},we=class extends ao{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var gl="v1",fl=300;async function ws(t,e,n,r=fl,o){return await yl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(ws,"constructEventAsync");function hl(t,e){return`${e.timestamp}.${t}`}s(hl,"makeHMACContent");async function yl(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=bl(t,e,gl),l=/\s/.test(n),p=await El(hl(a,u),n);return wl(a,i,u,p,r,c,l,o)}s(yl,"verifyHeaderAsync");function bl(t,e,n){if(!t)throw new we(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),i=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new we(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Rl(a,n);if(!u||u.timestamp===-1)throw new we(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new we(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(bl,"parseEventDetails");function wl(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(m=>Pl(m,r)).length,l=`
|
|
66
66
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,p=a?`
|
|
@@ -71,5 +71,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
71
71
|
`+p}):new we(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
72
72
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
73
73
|
`+l+`
|
|
74
|
-
`+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&d>o)throw new we(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(wl,"validateComputedSignature");function Rl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Rl,"parseHeader");function Pl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Pl,"secureCompare");async function El(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=uo[i[u]];return a.join("")}s(El,"computeHMACSignatureAsync");var uo=new Array(256);for(let t=0;t<uo.length;t++)uo[t]=t.toString(16).padStart(2,"0");function K(t,e){if(!Me(t))throw new h(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new h(`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 h(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new h(`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 h(`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 h(`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(K,"optionValidator");var tt=class extends de{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){K(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ws(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),T.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function Rs(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Rs,"isStripeWebhookEvent");var xn=class extends Re{static{s(this,"MeteringPlugin")}};var Il={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new C(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new C(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new C(i)}return o}},vn=Il;var co="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Ps({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=E.instance,c=new URL(`/v1/buckets/${t}/consumers`,co);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new C(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(Ps,"createConsumer");async function Es({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${t}/consumers`,co);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),d=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,d),new C(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(Es,"createConsumerInvite");async function Is({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,co);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new C(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(Is,"deleteConsumer");async function xs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:p}=E.instance;if(!Ge(l))throw new $("No Zuplo JWT token set.");let d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!d.ok){let m="Error creating metering subscription.",g;try{g=await d.json()}catch{g={status:d.status,statusText:d.statusText}}throw t.log.error(m,g),new C(m)}t.log.info("Successfully created/updated metering subscription.",c)}s(xs,"createSubscription");async function vt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new C(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(vt,"updateSubscription");async function Tt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new C(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new C(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new C(c)}return u.data[0]}s(Tt,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function lo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Ps({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Es({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return T.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await xs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await Is({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{detail:l.message})}return T.ok(t,e)}s(lo,"onCustomerSubscriptionCreated");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await vt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),T.ok(t,e)}s(po,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),T.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,p=(await vn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),d=0;return p.length===0?e.log.warn(`Not able to calculate proration details on plan change for subscription event '${n.id}'`):d=parseFloat(p[0].unit_amount_excluding_tax)/p[0].price.unit_amount,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}}),T.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),T.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var go=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:p,apiKeyBucketName:d}=this.options;if(!p)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)p=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new h("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.meteringBucketRegion??"us-central1";if(!xl(m))throw new h(`StripeMeteringPlugin - The value '${m}' on the property 'meteringBucketRegion' is invalid.`);let g=await c.json();if(!Rs(g))return T.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await lo(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await po(c,l,g,{meteringBucketId:p});default:return T.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Si({inboundPolicies:[new tt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new G({processors:[te,i],handler:o,gateway:r}),u=new V({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function xl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(xl,"isMetricsRegion");var Ts=new WeakMap,vs={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ts.set(e,n)}};async function Ss(t,e,n,r){if(!n.statusCodes)throw new h(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ts.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new C(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ue(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 p=a?.meterValue??n.meterValue;if(!p){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let d={customerId:c,meterApiName:l,meterValue:p,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=vs[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new B("amberflo-ingest-meter",10,async R=>{try{let v=n.url??"https://app.amberflo.io/ingest",k=await fetch(v,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});k.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${k.status}: ${await k.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),vs[g]=m}m.enqueue(d),e.waitUntil(m.waitUntilFlushed())}}),t}s(Ss,"AmberfloMeteringInboundPolicy");async function On(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(On,"sha256");var Os=new Map;async function Q(t,e){let n,r=Os.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,Os.set(t,n)),n}s(Q,"getPolicyCacheName");var Cs="key-metadata-cache-type";function vl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(vl,"getKeyValue");async function Cn(t,e,n,r){if(!n.bucketName)if(ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new h(`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 h(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(v=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:v}),"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=vl(a,o);if(!u||u==="")return i("No key present");let c=await Tl(u),l=await Q(r,o),p=new J(l,e),d=await p.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Cs&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let m={key:u},g=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${E.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":E.instance.deploymentName??"unknown","User-Agent":E.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let v=await g.text(),k=JSON.parse(v);e.log.error("Unexpected response from key service",k)}catch{e.log.error("Invalid response from key service")}throw new C(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),R={isValid:!0,typeId:Cs,user:{sub:I.name,data:I.metadata}};return t.user=R.user,p.put(c,R,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Tl(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(Tl,"hashValue");var As=Cn;var St=require("jose");var fo={},Sl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new h("Invalid State - jwkUrl not set");fo[e.jwkUrl]||(fo[e.jwkUrl]=(0,St.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,St.jwtVerify)(t,fo[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Ol=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,St.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),X=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(m=>T.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new h(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new h(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Sl:Ol,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 m=o.substring(i.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let p=n.subPropertyName??"sub",d=l[p];return d?(t.user={sub:d,data:l},t):a(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ls=s(async(t,e,n,r)=>X(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var _s=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>T.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 p=atob(l).normalize(),d=p.indexOf(":");if(d===-1||/[\0-\x1F\x7F]/.test(p))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=p.substring(0,d),g=p.substring(d+1),I=n.accounts.find(R=>R.username===m&&R.password===g);return I||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 Cl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Al(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Al,"digestMessage");var Ll=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[p,d]of t.headers.entries())n.includes(p)&&r.push({key:p.toLowerCase(),value:d});r.sort((p,d)=>p.key.localeCompare(d.key));let o=await Al(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 ks(t,e,n,r){let o=await Q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ll(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let p=n.statusCodes??[200,206,301,302,303,404,410],d=l.response.clone();if(!p.includes(d.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(d.body,d);Cl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(u,g))}catch(p){e.log.error(`Error in caching-inbound-policy '${r}': "${p.message}"`,p)}}),t)}s(ks,"CachingInboundPolicy");var Ds=s(async(t,e,n,r)=>{if(!n.method)throw new h(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ns=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 z(t,{headers:o})},"ClearHeadersInboundPolicy");var Ms=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 Us=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",X(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Hs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new h("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new h("region must be set in the options for CognitoJwtInboundPolicy");return X(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 Zs=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new h(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Y.instance,i=ht(n.policies,o?.routeData.policies);return Or(i)(t,e)},"CompositeInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let i=_l(o);if(!i)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Q(r,n),u=new J(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),p=await l.text();if(l.status===200)c=p,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${p}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function _l(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(_l,"getToken");var $s=s(async(t,e,n,r)=>(K(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),X(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 Fs=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[p,d]of a)u[p]=d.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new z(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var nt="__unknown__",Bs=s(async(t,e,n,r)=>{let o={allow:{countries:ot(n.allow?.countries,"allow.countries",r),regionCodes:ot(n.allow?.regionCodes,"allow.regionCode",r),asns:ot(n.allow?.asns,"allow.asOrganization",r)},block:{countries:ot(n.block?.countries,"block.countries",r),regionCodes:ot(n.block?.regionCodes,"block.regionCode",r),asns:ot(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??nt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??nt,u=e.incomingRequestProperties.asn?.toString()??nt,c=o.ignoreUnknown&&i===nt,l=o.ignoreUnknown&&a===nt,p=o.ignoreUnknown&&u===nt,d=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(d.length>0&&!d.includes(i)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!p)return rt(t,e,r,i,a,u);let I=o.block.countries,R=o.block.regionCodes,v=o.block.asns;return I.length>0&&I.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||v.length>0&&v.includes(u)&&!p?rt(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function rt(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(rt,"blockedResponse");function ot(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new h(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(ot,"toLowerStringArray");var js=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 Vs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return ho(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 ho(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 p=o[u].content[l].examples;p&&Object.keys(p).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:p[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return zs(a[u])}else return a.length>0?zs(a[0]):ho(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 zs(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(zs,"generateResponse");var ho=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var kl="Incoming",Dl={logRequestBody:!0,logResponseBody:!0};function Gs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Gs,"headersToObject");function Ws(){return new Date().toISOString()}s(Ws,"timestamp");var yo=new WeakMap,Nl={};function Ys(t,e){let n=yo.get(t);n||(n=Nl);let r=Object.assign({...n},e);yo.set(t,r)}s(Ys,"setMoesifContext");async function Ks(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Ks,"readBody");var Ml={},bo;function Js(){if(!bo)throw new C("Invalid State - no _lastLogger");return bo}s(Js,"getLastLogger");function Ul(t){let e=Ml[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Js().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||Js().error({status:o.status,body:await o.text()})})),e}s(Ul,"getDispatcher");async function Qs(t,e,n,r){bo=e.log;let o=Ws(),i=Object.assign(Dl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ks(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Ul(i.applicationId),p=t.headers.get("true-client-ip"),d=yo.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Gs(t.headers)},g=i.logResponseBody?await Ks(u,e):void 0,I={time:Ws(),status:u.status,headers:Gs(u.headers),body:g},R={request:m,response:I,user_id:d.userId??c.user?.sub,session_token:d.sessionToken,company_id:d.companyId,metadata:d.metadata,direction:kl};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),t}s(Qs,"MoesifInboundPolicy");async function Xs(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=E.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let p=await l.json(),d=p.detail??p.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${d}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${d}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(Xs,"loadSubscription");async function ea(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=E.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),p=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(ea,"consumeSubcriptionQuotas");var Hl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new h(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof h?new h(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(An,"validateMeters");function ta(t,e){if(t)try{if(t.length===0)throw new h("Must set valid subscription statuses");let n=He(t),r=[];for(let o of n)Hl.has(o)||r.push(o);if(r.length>0)throw new h(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof h?new h(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(ta,"parseAllowedSubscriptionStatuses");var Ln=class extends de{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,ct)}static setMeters(e,n){An(n,"setMeters"),le.set(e,Lt,n)}async handler(e,n){if(K(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new h(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let r=this.options.allowRequestsOverQuota??!1,o=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:zt(this.options.meterOnStatusCodes),i=le.get(n,Lt),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ta(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(R,v,k)=>{let f=le.get(k,ct);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){k.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(k,Lt),Z={...this.options.meters,...A};An(Z,this.policyName),o.includes(R.status)&&f&&Z&&(k.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${R.status}'`),await ea(k,f.id,this.policyName,this.options.bucketId,Z))});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await Xs(n,p,this.policyName,this.options.bucketId);if(!d)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(d.status)&&!u)return n.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(d.status)&&(n.log.debug(`Loading subscription '${d.id}' for user sub '${p}' to ContextData`),le.set(n,ct,d));let m=le.get(n,ct);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),T.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(R=>!Object.keys(m.meters).includes(R));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(m.meters[R].consumed<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var na=s(async(t,e,n,r)=>X(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ra=require("jose");var wo,oa=s(async(t,e,n,r)=>{if(!wo)try{wo=await(0,ra.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return X(t,e,{issuer:n.authUrl,secret:wo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var sa=_e(De());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Ro=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Po=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Zl(t,e){if(Pi(t))throw new Ro(e)}s(Zl,"throwIfUndefinedOrNull");function Ot(t,e){if(Zl(t,e),!se(t))throw new Po(e,"string")}s(Ot,"throwIfNotString");var kn=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 Ot(e,"redisClientUrl"),Ot(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}){Ot(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 $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Dn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ot(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 $("The in-memory redis client only supports /rate-limit calls")}};var Nn=(0,sa.debug)("zuplo:policies:RateLimitInboundPolicy"),ql="strict",$l=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"),Fl=s(async t=>({key:`ip-${$l(t)}`}),"getIP"),Bl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),jl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Mn;function zl(t,e){let n;if(Mn)return Mn;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Dn,Mn=n,n;let{authApiJWT:r,redisURL:o}=E.instance;if(!se(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=kn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Mn=n,n}s(zl,"getRedisClient");async function ia(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(ia,"getCountAndUpdateExpiry");function Vl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new h(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new h(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new h(`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 h(`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 C(c)}return u},"outerFunction")}s(Vl,"wrapUserFunction");var Gl="Retry-After",Eo=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new $(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let p={};return(!c||c==="retry-after")&&(p[Gl]=l.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let l={function:Vl(n,r),user:Bl,ip:Fl,all:jl}[n.rateLimitBy],p=await l(t,e,r),d=p.key,m=p.requestsAllowed??n.requestsAllowed,g=p.timeWindowMinutes??n.timeWindowMinutes,I=n.headerMode??"retry-after",R=zl(r,i),k=`bucket/${E.instance.build.BUILD_ID}/${r}/${d}`;if((n.mode??ql)==="async"){let A=await Q(r,n),Z=new Ee(A,{logger:F.getLogger(e)}),y=ia(k,g,R,i,e.requestId),w=await Z.get(k);if(w!==void 0&&w<=Date.now()){Nn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${k}' (async mode)`);let S=Math.round((w-Date.now())/1e3);return u(I,S)}return e.addEventListener("responseSending",S=>{try{let N=S,O=N.mutableResponse;N.mutableResponse=(async()=>{let _=await y;if(_.count>m){let D=Date.now()+_.ttlSeconds*1e3,L=Z.put(k,D,_.ttlSeconds).catch(q=>{throw i.error(new $("Error caching rate limit result.",{cause:q})),q});return e.waitUntil(L),Nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (async mode)`),u(I,_.ttlSeconds)}return O})()}catch(N){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,N)}}),t}let P=await ia(k,g,R,i,e.requestId);return P.count>m?(Nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (strict mode)`),u(I,P.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Nn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Io;function aa(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(aa,"headersToNameValuePairs");function Wl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Wl,"queryToNameValueParis");function Kl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Kl,"parseIntOrUndefined");var ua={};async function ca(t,e,n,r){let o=new Date,i=Date.now();return Io||(Io={name:"zuplo",version:E.instance.build.ZUPLO_VERSION,comment:`zuplo/${E.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ue(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ue(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:E.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Io,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:aa(t.headers),queryString:Wl(t.query)},response:{status:a.status,statusText:a.statusText,headers:aa(a.headers),content:{size:Kl(t.headers.get("content-length"))}}}]}}},p=ua[n.apiKey];if(!p){let d=n.apiKey;p=new B("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(d+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),ua[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ca,"ReadmeMetricsInboundPolicy");var la=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new h(`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 z(t,{headers:i})},"RemoveHeadersInboundPolicy");var da=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new h(`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 pa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new h(`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 z(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ma=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 ga=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),fa=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?ga():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ga():t},"RequestSizeLimitInboundPolicy");function ha(t,e,n){return`_${Ae(t+"_"+e+"_"+n)}`}s(ha,"getRawOperationDataIdentifierName");function Un(t,e,n,r){return`_${Ae(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Un,"getIdForParameterSchema");function Hn(t,e,n){return`_${Ae(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ae(n.toLowerCase())}`}s(Hn,"getIdForRequestBodySchema");function ya(t,e){return`_${Ae(t)}__${Ae(e)}`}s(ya,"getIdForRefSchema");function Ae(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(Ae,"sanitizedIdentifierName");var it=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"),st=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let p=Un(n,r,o,c.name),d=Y.instance.schemaValidator[p],m=d(e[c.name]),g=xo(d.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),ge=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),fe=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),xo=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 ba(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(ge(n.validateBody)&&me(t,n.logLevel??"info",I,[r],g),fe(n.validateBody))return R}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=T.badRequest(e,t,{detail:g});return ge(n.validateBody)&&me(t,n.logLevel??"info",g,[r],[g]),fe(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Hn(t.route.path,e.method,o),u=Y.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=T.badRequest(e,t,{detail:g});return ge(n.validateBody)&&me(t,n.logLevel??"info",g,[r],[g]),fe(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=xo(l),m=T.badRequest(e,t,{detail:`${p}, see errors property for more details`,errors:d});if(ge(n.validateBody)&&me(t,n.logLevel??"info",p,[r],d),fe(n.validateBody))return m}s(ba,"handleBodyValidation");function wa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=it(t),i=st(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(ge(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),fe(n.validateHeaders))return u}}s(wa,"handleHeadersValidation");function Ra(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=it(t),o=st(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=T.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),fe(n.validatePathParameters))return a}}s(Ra,"handlePathParameterValidation");function Pa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=it(t),o=st(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=T.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),fe(n.validateQueryParameters))return a}}s(Pa,"handleQueryParameterValidation");var vo=s(async(t,e,n)=>{let r=Pa(e,t,n);if(r!==void 0||(r=Ra(e,t,n),r!==void 0)||(r=wa(e,t,n),r!==void 0))return r;let o=await ba(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ea=vo;var Ia=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new h(`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 T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var xa=s(async(t,e,n)=>new z(t,{body:n.body}),"SetBodyInboundPolicy");var va=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new h(`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 h(`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 z(t,{headers:i})},"SetHeadersInboundPolicy");var Ta=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new h(`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 h(`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 Sa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new h(`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 h(`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 z(i.toString(),t)},"SetQueryParamsInboundPolicy");var Oa=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 Jl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ca=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new h(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Jl(n.sleepInMs),t},"SleepInboundPolicy");var Aa=s(async(t,e,n,r)=>{K(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await X(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof z))throw new $("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 C(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(p=>{let d=a[p];Array.isArray(d)?d.includes(u[p])||l.push(p):d!==u[p]&&l.push(p)}),l.length>0?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var La=s(async(t,e,n,r)=>{K(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Q(r,n),i=new J(o,e),a=await i.get(r);if(!a){let u=await Yl(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 Yl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new C("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 C("Response returned from Azure AD is not in the expected format.")}s(Yl,"getAccessToken");var _a="https://accounts.google.com/o/oauth2/token",To,ka=s(async(t,e,n,r)=>{K(n,r).required("serviceAccountJson","string"),To||(To=await ae.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 Q(r,n),a=new J(i,e),u=await a.get(r);if(!u){let c=await ye({serviceAccount:To,audience:_a,payload:o}),l=await en(_a,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new C("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 Ql="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Xl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],So,Da=s(async(t,e,n,r)=>{if(K(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new h(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(Xl.indexOf(d)!==-1)throw new h(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}So||(So=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new C("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 C(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ue(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new C(`Unable to determine user from for the policy ${r}`);let a=await Q(r,n),u=new J(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await ye({serviceAccount:So,audience:Ql,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await Hi(m,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new C("Invalid token response from Firebase");p=g.idToken,u.put(l,p,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${p}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Oo,Na=s(async(t,e,n,r)=>{K(n,r).required("audience","string").required("serviceAccountJson","string"),Oo||(Oo=await ae.init(n.serviceAccountJson));let o=await ye({serviceAccount:Oo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ma="https://www.googleapis.com/oauth2/v4/token",Co,Ua=s(async(t,e,n,r)=>{K(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Co||(Co=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new h("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=He(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof h?new h(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await Q(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new J(i,e);let u=await a.get(r);if(!u){let c=await ye({serviceAccount:Co,audience:Ma,payload:o}),l=await en(Ma,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new C("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new C("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Ha=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var $a=_e(qa());var Fa=s(async(t,e,n,r,o)=>{let i;try{let c=await t.text();i=new $a.default().parse(c)}catch(c){let l=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${o}'.`;throw n.log.error(l,c),new C(l)}let a=new Headers(t.headers);return a.set("content-type","application/json"),new Response(JSON.stringify(i),{status:t.status,statusText:t.statusText,headers:a})},"XmlToJsonOutboundPolicy");var Zn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`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 Lo=["sha-1","sha-256","sha-384","sha-512"],qn=class{static{s(this,"BaseCryptoBeta")}};var $n=class extends qn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Lo.includes(e.toLowerCase()))throw new C(`Algorithm ${e} is not supported. Try using ${Lo.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 Fn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Bn=class extends Fn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new Ct("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new h("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)}};
|
|
74
|
+
`+p});let d=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&d>o)throw new we(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(wl,"validateComputedSignature");function Rl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Rl,"parseHeader");function Pl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Pl,"secureCompare");async function El(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=uo[i[u]];return a.join("")}s(El,"computeHMACSignatureAsync");var uo=new Array(256);for(let t=0;t<uo.length;t++)uo[t]=t.toString(16).padStart(2,"0");function J(t,e){if(!Me(t))throw new h(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new h(`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 h(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new h(`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 h(`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 h(`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(J,"optionValidator");var tt=class extends de{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){J(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ws(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),T.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function Rs(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Rs,"isStripeWebhookEvent");var xn=class extends Re{static{s(this,"MeteringPlugin")}};var Il={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new C(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new C(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new C(i)}return o}},vn=Il;var co="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Ps({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=E.instance,c=new URL(`/v1/buckets/${t}/consumers`,co);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),p={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new C(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(Ps,"createConsumer");async function Es({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=E.instance,u=new URL(`/v1/buckets/${t}/consumers`,co);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),d=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,d),new C(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(Es,"createConsumerInvite");async function Is({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=E.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,co);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new C(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(Is,"deleteConsumer");async function xs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:p}=E.instance;if(!Ge(l))throw new $("No Zuplo JWT token set.");let d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!d.ok){let m="Error creating metering subscription.",g;try{g=await d.json()}catch{g={status:d.status,statusText:d.statusText}}throw t.log.error(m,g),new C(m)}t.log.info("Successfully created/updated metering subscription.",c)}s(xs,"createSubscription");async function vt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new C(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(vt,"updateSubscription");async function Tt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=E.instance;if(!Ge(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new C(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new C(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new C(c)}return u.data[0]}s(Tt,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function lo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Ps({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Es({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return T.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await xs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await Is({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{detail:l.message})}return T.ok(t,e)}s(lo,"onCustomerSubscriptionCreated");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await vt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),T.ok(t,e)}s(po,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),T.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await Tt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,l=await vn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey});e.log.debug(`upcoming invoice: ${JSON.stringify(l)}`);let p=l.lines.data.filter(m=>(e.log.debug(`line item from invoice: ${JSON.stringify(m)}`),m.proration&&m.price.product===c)),d=0;return p.length===0?e.log.warn(`Not able to calculate proration details on plan change for subscription event '${n.id}'`):d=parseFloat(p[0].unit_amount_excluding_tax)/p[0].price.unit_amount,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:d}}),T.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),T.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var go=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:p,apiKeyBucketName:d}=this.options;if(!p)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)p=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new h("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!E.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.meteringBucketRegion??"us-central1";if(!xl(m))throw new h(`StripeMeteringPlugin - The value '${m}' on the property 'meteringBucketRegion' is invalid.`);let g=await c.json();if(!Rs(g))return T.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await lo(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,g,{meteringBucketId:p,apiKeyBucketName:d,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await po(c,l,g,{meteringBucketId:p});default:return T.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Si({inboundPolicies:[new tt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new G({processors:[te,i],handler:o,gateway:r}),u=new V({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function xl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(xl,"isMetricsRegion");var Ts=new WeakMap,vs={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ts.set(e,n)}};async function Ss(t,e,n,r){if(!n.statusCodes)throw new h(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:zt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ts.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new C(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ue(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 p=a?.meterValue??n.meterValue;if(!p){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let d={customerId:c,meterApiName:l,meterValue:p,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=vs[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new B("amberflo-ingest-meter",10,async R=>{try{let v=n.url??"https://app.amberflo.io/ingest",k=await fetch(v,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});k.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${k.status}: ${await k.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),vs[g]=m}m.enqueue(d),e.waitUntil(m.waitUntilFlushed())}}),t}s(Ss,"AmberfloMeteringInboundPolicy");async function On(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(On,"sha256");var Os=new Map;async function Q(t,e){let n,r=Os.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,Os.set(t,n)),n}s(Q,"getPolicyCacheName");var Cs="key-metadata-cache-type";function vl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(vl,"getKeyValue");async function Cn(t,e,n,r){if(!n.bucketName)if(ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ne.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new h(`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 h(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(v=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:v}),"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=vl(a,o);if(!u||u==="")return i("No key present");let c=await Tl(u),l=await Q(r,o),p=new K(l,e),d=await p.get(c);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==Cs&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${d.typeId}'`,d),i("Authorization Failed");let m={key:u},g=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${E.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":E.instance.deploymentName??"unknown","User-Agent":E.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let v=await g.text(),k=JSON.parse(v);e.log.error("Unexpected response from key service",k)}catch{e.log.error("Invalid response from key service")}throw new C(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),R={isValid:!0,typeId:Cs,user:{sub:I.name,data:I.metadata}};return t.user=R.user,p.put(c,R,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Tl(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(Tl,"hashValue");var As=Cn;var St=require("jose");var fo={},Sl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new h("Invalid State - jwkUrl not set");fo[e.jwkUrl]||(fo[e.jwkUrl]=(0,St.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,St.jwtVerify)(t,fo[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Ol=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,St.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),X=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(m=>T.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new h(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new h(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Sl:Ol,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 m=o.substring(i.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let p=n.subPropertyName??"sub",d=l[p];return d?(t.user={sub:d,data:l},t):a(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ls=s(async(t,e,n,r)=>X(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var _s=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>T.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 p=atob(l).normalize(),d=p.indexOf(":");if(d===-1||/[\0-\x1F\x7F]/.test(p))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=p.substring(0,d),g=p.substring(d+1),I=n.accounts.find(R=>R.username===m&&R.password===g);return I||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 Cl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Al(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Al,"digestMessage");var Ll=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[p,d]of t.headers.entries())n.includes(p)&&r.push({key:p.toLowerCase(),value:d});r.sort((p,d)=>p.key.localeCompare(d.key));let o=await Al(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 ks(t,e,n,r){let o=await Q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ll(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let p=n.statusCodes??[200,206,301,302,303,404,410],d=l.response.clone();if(!p.includes(d.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(d.body,d);Cl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(u,g))}catch(p){e.log.error(`Error in caching-inbound-policy '${r}': "${p.message}"`,p)}}),t)}s(ks,"CachingInboundPolicy");var Ds=s(async(t,e,n,r)=>{if(!n.method)throw new h(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new z(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ns=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 z(t,{headers:o})},"ClearHeadersInboundPolicy");var Ms=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 Us=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",X(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Hs=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new h("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new h("region must be set in the options for CognitoJwtInboundPolicy");return X(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 Zs=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new h(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Y.instance,i=ht(n.policies,o?.routeData.policies);return Or(i)(t,e)},"CompositeInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let i=_l(o);if(!i)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Q(r,n),u=new K(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),p=await l.text();if(l.status===200)c=p,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${p}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function _l(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(_l,"getToken");var $s=s(async(t,e,n,r)=>(J(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),X(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 Fs=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[p,d]of a)u[p]=d.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new z(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var nt="__unknown__",Bs=s(async(t,e,n,r)=>{let o={allow:{countries:ot(n.allow?.countries,"allow.countries",r),regionCodes:ot(n.allow?.regionCodes,"allow.regionCode",r),asns:ot(n.allow?.asns,"allow.asOrganization",r)},block:{countries:ot(n.block?.countries,"block.countries",r),regionCodes:ot(n.block?.regionCodes,"block.regionCode",r),asns:ot(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??nt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??nt,u=e.incomingRequestProperties.asn?.toString()??nt,c=o.ignoreUnknown&&i===nt,l=o.ignoreUnknown&&a===nt,p=o.ignoreUnknown&&u===nt,d=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(d.length>0&&!d.includes(i)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!p)return rt(t,e,r,i,a,u);let I=o.block.countries,R=o.block.regionCodes,v=o.block.asns;return I.length>0&&I.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||v.length>0&&v.includes(u)&&!p?rt(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function rt(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(rt,"blockedResponse");function ot(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new h(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(ot,"toLowerStringArray");var js=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 Vs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return ho(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 ho(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 p=o[u].content[l].examples;p&&Object.keys(p).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:p[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return zs(a[u])}else return a.length>0?zs(a[0]):ho(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 zs(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(zs,"generateResponse");var ho=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var kl="Incoming",Dl={logRequestBody:!0,logResponseBody:!0};function Gs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Gs,"headersToObject");function Ws(){return new Date().toISOString()}s(Ws,"timestamp");var yo=new WeakMap,Nl={};function Ys(t,e){let n=yo.get(t);n||(n=Nl);let r=Object.assign({...n},e);yo.set(t,r)}s(Ys,"setMoesifContext");async function Js(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Js,"readBody");var Ml={},bo;function Ks(){if(!bo)throw new C("Invalid State - no _lastLogger");return bo}s(Ks,"getLastLogger");function Ul(t){let e=Ml[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ks().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||Ks().error({status:o.status,body:await o.text()})})),e}s(Ul,"getDispatcher");async function Qs(t,e,n,r){bo=e.log;let o=Ws(),i=Object.assign(Dl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Js(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Ul(i.applicationId),p=t.headers.get("true-client-ip"),d=yo.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:p??void 0,api_version:d.apiVersion,headers:Gs(t.headers)},g=i.logResponseBody?await Js(u,e):void 0,I={time:Ws(),status:u.status,headers:Gs(u.headers),body:g},R={request:m,response:I,user_id:d.userId??c.user?.sub,session_token:d.sessionToken,company_id:d.companyId,metadata:d.metadata,direction:kl};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),t}s(Qs,"MoesifInboundPolicy");async function Xs(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=E.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let p=await l.json(),d=p.detail??p.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${d}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${d}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(Xs,"loadSubscription");async function ea(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=E.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),p=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${p}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(ea,"consumeSubcriptionQuotas");var Hl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new h(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof h?new h(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(An,"validateMeters");function ta(t,e){if(t)try{if(t.length===0)throw new h("Must set valid subscription statuses");let n=He(t),r=[];for(let o of n)Hl.has(o)||r.push(o);if(r.length>0)throw new h(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof h?new h(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(ta,"parseAllowedSubscriptionStatuses");var Ln=class extends de{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,ct)}static setMeters(e,n){An(n,"setMeters"),le.set(e,Lt,n)}async handler(e,n){if(J(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new h(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let r=this.options.allowRequestsOverQuota??!1,o=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:zt(this.options.meterOnStatusCodes),i=le.get(n,Lt),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ta(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(R,v,k)=>{let f=le.get(k,ct);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){k.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let A=le.get(k,Lt),Z={...this.options.meters,...A};An(Z,this.policyName),o.includes(R.status)&&f&&Z&&(k.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${R.status}'`),await ea(k,f.id,this.policyName,this.options.bucketId,Z))});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ne.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ne.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new h(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:p}=l,d=await Xs(n,p,this.policyName,this.options.bucketId);if(!d)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(d.status)&&!u)return n.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(d.status)&&(n.log.debug(`Loading subscription '${d.id}' for user sub '${p}' to ContextData`),le.set(n,ct,d));let m=le.get(n,ct);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),T.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(R=>!Object.keys(m.meters).includes(R));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(m.meters[R].consumed<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var na=s(async(t,e,n,r)=>X(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var ra=require("jose");var wo,oa=s(async(t,e,n,r)=>{if(!wo)try{wo=await(0,ra.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return X(t,e,{issuer:n.authUrl,secret:wo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var sa=_e(De());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Ro=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Po=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Zl(t,e){if(Pi(t))throw new Ro(e)}s(Zl,"throwIfUndefinedOrNull");function Ot(t,e){if(Zl(t,e),!se(t))throw new Po(e,"string")}s(Ot,"throwIfNotString");var kn=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 Ot(e,"redisClientUrl"),Ot(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}){Ot(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 $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Dn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ot(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 $("The in-memory redis client only supports /rate-limit calls")}};var Nn=(0,sa.debug)("zuplo:policies:RateLimitInboundPolicy"),ql="strict",$l=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"),Fl=s(async t=>({key:`ip-${$l(t)}`}),"getIP"),Bl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),jl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Mn;function zl(t,e){let n;if(Mn)return Mn;if(E.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Dn,Mn=n,n;let{authApiJWT:r,redisURL:o}=E.instance;if(!se(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=kn.initialize(o,r,E.instance.deploymentName??"unknown",E.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Mn=n,n}s(zl,"getRedisClient");async function ia(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(ia,"getCountAndUpdateExpiry");function Vl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new h(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new h(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new h(`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 h(`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 C(c)}return u},"outerFunction")}s(Vl,"wrapUserFunction");var Gl="Retry-After",Eo=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new $(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let p={};return(!c||c==="retry-after")&&(p[Gl]=l.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let l={function:Vl(n,r),user:Bl,ip:Fl,all:jl}[n.rateLimitBy],p=await l(t,e,r),d=p.key,m=p.requestsAllowed??n.requestsAllowed,g=p.timeWindowMinutes??n.timeWindowMinutes,I=n.headerMode??"retry-after",R=zl(r,i),k=`bucket/${E.instance.build.BUILD_ID}/${r}/${d}`;if((n.mode??ql)==="async"){let A=await Q(r,n),Z=new Ee(A,{logger:F.getLogger(e)}),y=ia(k,g,R,i,e.requestId),w=await Z.get(k);if(w!==void 0&&w<=Date.now()){Nn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${k}' (async mode)`);let S=Math.round((w-Date.now())/1e3);return u(I,S)}return e.addEventListener("responseSending",S=>{try{let N=S,O=N.mutableResponse;N.mutableResponse=(async()=>{let _=await y;if(_.count>m){let D=Date.now()+_.ttlSeconds*1e3,L=Z.put(k,D,_.ttlSeconds).catch(q=>{throw i.error(new $("Error caching rate limit result.",{cause:q})),q});return e.waitUntil(L),Nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (async mode)`),u(I,_.ttlSeconds)}return O})()}catch(N){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,N)}}),t}let P=await ia(k,g,R,i,e.requestId);return P.count>m?(Nn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (strict mode)`),u(I,P.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Nn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Io;function aa(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(aa,"headersToNameValuePairs");function Wl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Wl,"queryToNameValueParis");function Jl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Jl,"parseIntOrUndefined");var ua={};async function ca(t,e,n,r){let o=new Date,i=Date.now();return Io||(Io={name:"zuplo",version:E.instance.build.ZUPLO_VERSION,comment:`zuplo/${E.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ue(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ue(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:E.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Io,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:aa(t.headers),queryString:Wl(t.query)},response:{status:a.status,statusText:a.statusText,headers:aa(a.headers),content:{size:Jl(t.headers.get("content-length"))}}}]}}},p=ua[n.apiKey];if(!p){let d=n.apiKey;p=new B("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(d+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),ua[d]=p}p.enqueue(l),e.waitUntil(p.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(ca,"ReadmeMetricsInboundPolicy");var la=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new h(`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 z(t,{headers:i})},"RemoveHeadersInboundPolicy");var da=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new h(`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 pa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new h(`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 z(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ma=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 ga=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),fa=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?ga():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ga():t},"RequestSizeLimitInboundPolicy");function ha(t,e,n){return`_${Ae(t+"_"+e+"_"+n)}`}s(ha,"getRawOperationDataIdentifierName");function Un(t,e,n,r){return`_${Ae(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Un,"getIdForParameterSchema");function Hn(t,e,n){return`_${Ae(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ae(n.toLowerCase())}`}s(Hn,"getIdForRequestBodySchema");function ya(t,e){return`_${Ae(t)}__${Ae(e)}`}s(ya,"getIdForRefSchema");function Ae(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(Ae,"sanitizedIdentifierName");var it=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"),st=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let p=Un(n,r,o,c.name),d=Y.instance.schemaValidator[p],m=d(e[c.name]),g=xo(d.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),ge=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),fe=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),xo=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 ba(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(ge(n.validateBody)&&me(t,n.logLevel??"info",I,[r],g),fe(n.validateBody))return R}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=T.badRequest(e,t,{detail:g});return ge(n.validateBody)&&me(t,n.logLevel??"info",g,[r],[g]),fe(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Hn(t.route.path,e.method,o),u=Y.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=T.badRequest(e,t,{detail:g});return ge(n.validateBody)&&me(t,n.logLevel??"info",g,[r],[g]),fe(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,p="Request body did not pass validation",d=xo(l),m=T.badRequest(e,t,{detail:`${p}, see errors property for more details`,errors:d});if(ge(n.validateBody)&&me(t,n.logLevel??"info",p,[r],d),fe(n.validateBody))return m}s(ba,"handleBodyValidation");function wa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=it(t),i=st(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(ge(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),fe(n.validateHeaders))return u}}s(wa,"handleHeadersValidation");function Ra(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=it(t),o=st(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=T.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),fe(n.validatePathParameters))return a}}s(Ra,"handlePathParameterValidation");function Pa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=it(t),o=st(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=T.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(ge(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),fe(n.validateQueryParameters))return a}}s(Pa,"handleQueryParameterValidation");var vo=s(async(t,e,n)=>{let r=Pa(e,t,n);if(r!==void 0||(r=Ra(e,t,n),r!==void 0)||(r=wa(e,t,n),r!==void 0))return r;let o=await ba(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ea=vo;var Ia=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new h(`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 T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var xa=s(async(t,e,n)=>new z(t,{body:n.body}),"SetBodyInboundPolicy");var va=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new h(`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 h(`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 z(t,{headers:i})},"SetHeadersInboundPolicy");var Ta=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new h(`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 h(`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 Sa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new h(`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 h(`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 z(i.toString(),t)},"SetQueryParamsInboundPolicy");var Oa=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 Kl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ca=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new h(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Kl(n.sleepInMs),t},"SleepInboundPolicy");var Aa=s(async(t,e,n,r)=>{J(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await X(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof z))throw new $("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 C(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(p=>{let d=a[p];Array.isArray(d)?d.includes(u[p])||l.push(p):d!==u[p]&&l.push(p)}),l.length>0?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var La=s(async(t,e,n,r)=>{J(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Q(r,n),i=new K(o,e),a=await i.get(r);if(!a){let u=await Yl(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 Yl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new C("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 C("Response returned from Azure AD is not in the expected format.")}s(Yl,"getAccessToken");var _a="https://accounts.google.com/o/oauth2/token",To,ka=s(async(t,e,n,r)=>{J(n,r).required("serviceAccountJson","string"),To||(To=await ae.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 Q(r,n),a=new K(i,e),u=await a.get(r);if(!u){let c=await ye({serviceAccount:To,audience:_a,payload:o}),l=await en(_a,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new C("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 Ql="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Xl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],So,Da=s(async(t,e,n,r)=>{if(J(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new h(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let d in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,d)){if(Xl.indexOf(d)!==-1)throw new h(`Developer claim "${d}" is reserved and cannot be specified.`);o[d]=n.developerClaims[d]}}So||(So=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new C("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 C(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ue(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new C(`Unable to determine user from for the policy ${r}`);let a=await Q(r,n),u=new K(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),p=await u.get(l);if(!p){let d=await ye({serviceAccount:So,audience:Ql,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await Hi(m,d,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new C("Invalid token response from Firebase");p=g.idToken,u.put(l,p,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${p}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Oo,Na=s(async(t,e,n,r)=>{J(n,r).required("audience","string").required("serviceAccountJson","string"),Oo||(Oo=await ae.init(n.serviceAccountJson));let o=await ye({serviceAccount:Oo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ma="https://www.googleapis.com/oauth2/v4/token",Co,Ua=s(async(t,e,n,r)=>{J(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Co||(Co=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new h("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=He(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof h?new h(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await Q(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new K(i,e);let u=await a.get(r);if(!u){let c=await ye({serviceAccount:Co,audience:Ma,payload:o}),l=await en(Ma,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new C("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new C("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Ha=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var $a=_e(qa());var Fa=s(async(t,e,n,r,o)=>{let i;try{let c=await t.text();i=new $a.default().parse(c)}catch(c){let l=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${o}'.`;throw n.log.error(l,c),new C(l)}let a=new Headers(t.headers);return a.set("content-type","application/json"),new Response(JSON.stringify(i),{status:t.status,statusText:t.statusText,headers:a})},"XmlToJsonOutboundPolicy");var Zn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`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 Lo=["sha-1","sha-256","sha-384","sha-512"],qn=class{static{s(this,"BaseCryptoBeta")}};var $n=class extends qn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Lo.includes(e.toLowerCase()))throw new C(`Algorithm ${e} is not supported. Try using ${Lo.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 Fn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Bn=class extends Fn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new Ct("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new h("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)}};
|
|
75
75
|
/*! For license information please see index.minified.js.LEGAL.txt */
|