@zuplo/runtime 5.1855.0 → 5.1858.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 +3 -3
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
`))):u=t.stylize("[Circular]","special")),xi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}i(xr,"formatProperty");function Pc(t,e){if(xi(e))return t.stylize("undefined","undefined");if(vi(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(bc(e))return t.stylize(""+e,"number");if(hc(e))return t.stylize(""+e,"boolean");if(Ti(e))return t.stylize("null","null")}i(Pc,"formatPrimitive");function Ec(t,e,n){let r=0;return t.reduce(function(s,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,s+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]}i(Ec,"reduceToSingleString")});var Ci=Fe(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.format=void 0;var Ic=Ei(),xc=Si(),vc=i((t,...e)=>(0,Ic.format)(xc.inspect,t,e),"format");Ut.format=vc});var Se=Fe(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.debug=Oe.withoutEnv=Oe.Debugger=void 0;var Tc=Pi(),Oc=Ci(),Ht=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Tc.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,Oc.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Oe.Debugger=Ht;var Zt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ai(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Ai,"extract");var dt;function Sc(t){t||(t=[]),typeof t=="string"&&(t=Ai(t)),dt=new Zt(t)}i(Sc,"withoutEnv");Oe.withoutEnv=Sc;function Cc(t){let e=globalThis.DEBUG;dt||(dt=new Zt(Ai(e)));let n=new Ht(dt,t);return dt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(Cc,"debug");Oe.debug=Cc});var fu=Fe((
|
|
35
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}i(Ec,"reduceToSingleString")});var Ci=Fe(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.format=void 0;var Ic=Ei(),xc=Si(),vc=i((t,...e)=>(0,Ic.format)(xc.inspect,t,e),"format");Ut.format=vc});var Se=Fe(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.debug=Oe.withoutEnv=Oe.Debugger=void 0;var Tc=Pi(),Oc=Ci(),Ht=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Tc.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,Oc.format)(n,...e);let s=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Oe.Debugger=Ht;var Zt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ai(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}i(Ai,"extract");var dt;function Sc(t){t||(t=[]),typeof t=="string"&&(t=Ai(t)),dt=new Zt(t)}i(Sc,"withoutEnv");Oe.withoutEnv=Sc;function Cc(t){let e=globalThis.DEBUG;dt||(dt=new Zt(Ai(e)));let n=new Ht(dt,t);return dt.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}i(Cc,"debug");Oe.debug=Cc});var fu=Fe((wT,mu)=>{"use strict";var Ed=Object.defineProperty,Id=Object.getOwnPropertyNames,D=i((t,e)=>Ed(t,"name",{value:e,configurable:!0}),"__name"),ye=i((t,e)=>i(function(){return e||(0,t[Id(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Bo=ye({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",o=new RegExp("^"+r+"$"),s=D(function(u,c){let l=[],d=c.exec(u);for(;d;){let p=[];p.startIndex=c.lastIndex-d[0].length;let g=d.length;for(let m=0;m<g;m++)p.push(d[m]);l.push(p),d=c.exec(u)}return l},"getAllMatches"),a=D(function(u){let c=o.exec(u);return!(c===null||typeof c>"u")},"isName");t.isExist=function(u){return typeof u<"u"},t.isEmptyObject=function(u){return Object.keys(u).length===0},t.merge=function(u,c,l){if(c){let d=Object.keys(c),p=d.length;for(let g=0;g<p;g++)l==="strict"?u[d[g]]=[c[d[g]]]:u[d[g]]=c[d[g]]}},t.getValue=function(u){return t.isExist(u)?u:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r}}),gu=ye({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Bo(),n={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(f,E){E=Object.assign({},n,E);let C=[],U=!1,h=!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 O=w;if(w++,f[w]==="!"){w=s(f,w);continue}else{let M=!1;f[w]==="/"&&(M=!0,w++);let A="";for(;w<f.length&&f[w]!==">"&&f[w]!==" "&&f[w]!==" "&&f[w]!==`
|
|
36
36
|
`&&f[w]!=="\r";w++)A+=f[w];if(A=A.trim(),A[A.length-1]==="/"&&(A=A.substring(0,A.length-1),w--),!b(A)){let k;return A.trim().length===0?k="Invalid space after '<'.":k="Tag '"+A+"' is an invalid name.",m("InvalidTag",k,v(f,w))}let _=c(f,w);if(_===!1)return m("InvalidAttr","Attributes for '"+A+"' have open quote.",v(f,w));let B=_.value;if(w=_.index,B[B.length-1]==="/"){let k=w-B.length;B=B.substring(0,B.length-1);let N=d(B,E);if(N===!0)U=!0;else return m(N.err.code,N.err.msg,v(f,k+N.err.line))}else if(M)if(_.tagClosed){if(B.trim().length>0)return m("InvalidTag","Closing tag '"+A+"' can't have attributes or invalid starting.",v(f,O));{let k=C.pop();if(A!==k.tagName){let N=v(f,k.tagStartPos);return m("InvalidTag","Expected closing tag '"+k.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+A+"'.",v(f,O))}C.length==0&&(h=!0)}}else return m("InvalidTag","Closing tag '"+A+"' doesn't have proper closing.",v(f,w));else{let k=d(B,E);if(k!==!0)return m(k.err.code,k.err.msg,v(f,w-B.length+k.err.line));if(h===!0)return m("InvalidXml","Multiple possible root nodes found.",v(f,w));E.unpairedTags.indexOf(A)!==-1||C.push({tagName:A,tagStartPos:O}),U=!0}for(w++;w<f.length;w++)if(f[w]==="<")if(f[w+1]==="!"){w++,w=s(f,w);continue}else if(f[w+1]==="?"){if(w=o(f,++w),w.err)return w}else break;else if(f[w]==="&"){let k=g(f,w);if(k==-1)return m("InvalidChar","char '&' is not expected.",v(f,w));w=k}else if(h===!0&&!r(f[w]))return m("InvalidXml","Extra text at the end",v(f,w));f[w]==="<"&&w--}}else{if(r(f[w]))continue;return m("InvalidChar","char '"+f[w]+"' is not expected.",v(f,w))}if(U){if(C.length==1)return m("InvalidTag","Unclosed tag '"+C[0].tagName+"'.",v(f,C[0].tagStartPos));if(C.length>0)return m("InvalidXml","Invalid '"+JSON.stringify(C.map(w=>w.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return m("InvalidXml","Start tag expected.",1);return!0};function r(f){return f===" "||f===" "||f===`
|
|
37
37
|
`||f==="\r"}i(r,"isWhiteSpace"),D(r,"isWhiteSpace");function o(f,E){let C=E;for(;E<f.length;E++)if(f[E]=="?"||f[E]==" "){let U=f.substr(C,E-C);if(E>5&&U==="xml")return m("InvalidXml","XML declaration allowed only at the start of the document.",v(f,E));if(f[E]=="?"&&f[E+1]==">"){E++;break}else continue}return E}i(o,"readPI"),D(o,"readPI");function s(f,E){if(f.length>E+5&&f[E+1]==="-"&&f[E+2]==="-"){for(E+=3;E<f.length;E++)if(f[E]==="-"&&f[E+1]==="-"&&f[E+2]===">"){E+=2;break}}else if(f.length>E+8&&f[E+1]==="D"&&f[E+2]==="O"&&f[E+3]==="C"&&f[E+4]==="T"&&f[E+5]==="Y"&&f[E+6]==="P"&&f[E+7]==="E"){let C=1;for(E+=8;E<f.length;E++)if(f[E]==="<")C++;else if(f[E]===">"&&(C--,C===0))break}else if(f.length>E+9&&f[E+1]==="["&&f[E+2]==="C"&&f[E+3]==="D"&&f[E+4]==="A"&&f[E+5]==="T"&&f[E+6]==="A"&&f[E+7]==="["){for(E+=8;E<f.length;E++)if(f[E]==="]"&&f[E+1]==="]"&&f[E+2]===">"){E+=2;break}}return E}i(s,"readCommentAndCDATA"),D(s,"readCommentAndCDATA");var a='"',u="'";function c(f,E){let C="",U="",h=!1;for(;E<f.length;E++){if(f[E]===a||f[E]===u)U===""?U=f[E]:U!==f[E]||(U="");else if(f[E]===">"&&U===""){h=!0;break}C+=f[E]}return U!==""?!1:{value:C,index:E,tagClosed:h}}i(c,"readAttributeStr"),D(c,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(f,E){let C=e.getAllMatches(f,l),U={};for(let h=0;h<C.length;h++){if(C[h][1].length===0)return m("InvalidAttr","Attribute '"+C[h][2]+"' has no space in starting.",S(C[h]));if(C[h][3]!==void 0&&C[h][4]===void 0)return m("InvalidAttr","Attribute '"+C[h][2]+"' is without value.",S(C[h]));if(C[h][3]===void 0&&!E.allowBooleanAttributes)return m("InvalidAttr","boolean attribute '"+C[h][2]+"' is not allowed.",S(C[h]));let w=C[h][2];if(!R(w))return m("InvalidAttr","Attribute '"+w+"' is an invalid name.",S(C[h]));if(!U.hasOwnProperty(w))U[w]=1;else return m("InvalidAttr","Attribute '"+w+"' is repeated.",S(C[h]))}return!0}i(d,"validateAttributeString"),D(d,"validateAttributeString");function p(f,E){let C=/\d/;for(f[E]==="x"&&(E++,C=/[\da-fA-F]/);E<f.length;E++){if(f[E]===";")return E;if(!f[E].match(C))break}return-1}i(p,"validateNumberAmpersand"),D(p,"validateNumberAmpersand");function g(f,E){if(E++,f[E]===";")return-1;if(f[E]==="#")return E++,p(f,E);let C=0;for(;E<f.length;E++,C++)if(!(f[E].match(/\w/)&&C<20)){if(f[E]===";")break;return-1}return E}i(g,"validateAmpersand"),D(g,"validateAmpersand");function m(f,E,C){return{err:{code:f,msg:E,line:C.line||C,col:C.col}}}i(m,"getErrorObject"),D(m,"getErrorObject");function R(f){return e.isName(f)}i(R,"validateAttrName"),D(R,"validateAttrName");function b(f){return e.isName(f)}i(b,"validateTagName"),D(b,"validateTagName");function v(f,E){let C=f.substring(0,E).split(/\r?\n/);return{line:C.length,col:C[C.length-1].length+1}}i(v,"getLineNumberForPosition"),D(v,"getLineNumberForPosition");function S(f){return f.startIndex+f[1].length}i(S,"getPositionFromMatch"),D(S,"getPositionFromMatch")}}),xd=ye({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(r,o){return o},attributeValueProcessor:function(r,o){return o},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(r,o,s){return r}},n=D(function(r){return Object.assign({},e,r)},"buildOptions");t.buildOptions=n,t.defaultOptions=e}}),vd=ye({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var n=class{static{i(this,"XmlNode")}static{D(this,"XmlNode")}constructor(r){this.tagname=r,this.child=[],this[":@"]={}}add(r,o){r==="__proto__"&&(r="#__proto__"),this.child.push({[r]:o})}addChild(r){r.tagname==="__proto__"&&(r.tagname="#__proto__"),r[":@"]&&Object.keys(r[":@"]).length>0?this.child.push({[r.tagname]:r.child,":@":r[":@"]}):this.child.push({[r.tagname]:r.child})}};e.exports=n}}),Td=ye({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var n=Bo();function r(p,g){let m={};if(p[g+3]==="O"&&p[g+4]==="C"&&p[g+5]==="T"&&p[g+6]==="Y"&&p[g+7]==="P"&&p[g+8]==="E"){g=g+9;let R=1,b=!1,v=!1,S="";for(;g<p.length;g++)if(p[g]==="<"&&!v){if(b&&a(p,g))g+=7,[entityName,val,g]=o(p,g+1),val.indexOf("&")===-1&&(m[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&u(p,g))g+=8;else if(b&&c(p,g))g+=8;else if(b&&l(p,g))g+=9;else if(s)v=!0;else throw new Error("Invalid DOCTYPE");R++,S=""}else if(p[g]===">"){if(v?p[g-1]==="-"&&p[g-2]==="-"&&(v=!1,R--):R--,R===0)break}else p[g]==="["?b=!0:S+=p[g];if(R!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:m,i:g}}i(r,"readDocType"),D(r,"readDocType");function o(p,g){let m="";for(;g<p.length&&p[g]!=="'"&&p[g]!=='"';g++)m+=p[g];if(m=m.trim(),m.indexOf(" ")!==-1)throw new Error("External entites are not supported");let R=p[g++],b="";for(;g<p.length&&p[g]!==R;g++)b+=p[g];return[m,b,g]}i(o,"readEntityExp"),D(o,"readEntityExp");function s(p,g){return p[g+1]==="!"&&p[g+2]==="-"&&p[g+3]==="-"}i(s,"isComment"),D(s,"isComment");function a(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="N"&&p[g+4]==="T"&&p[g+5]==="I"&&p[g+6]==="T"&&p[g+7]==="Y"}i(a,"isEntity"),D(a,"isEntity");function u(p,g){return p[g+1]==="!"&&p[g+2]==="E"&&p[g+3]==="L"&&p[g+4]==="E"&&p[g+5]==="M"&&p[g+6]==="E"&&p[g+7]==="N"&&p[g+8]==="T"}i(u,"isElement"),D(u,"isElement");function c(p,g){return p[g+1]==="!"&&p[g+2]==="A"&&p[g+3]==="T"&&p[g+4]==="T"&&p[g+5]==="L"&&p[g+6]==="I"&&p[g+7]==="S"&&p[g+8]==="T"}i(c,"isAttlist"),D(c,"isAttlist");function l(p,g){return p[g+1]==="!"&&p[g+2]==="N"&&p[g+3]==="O"&&p[g+4]==="T"&&p[g+5]==="A"&&p[g+6]==="T"&&p[g+7]==="I"&&p[g+8]==="O"&&p[g+9]==="N"}i(l,"isNotation"),D(l,"isNotation");function d(p){if(n.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}i(d,"validateEntityName"),D(d,"validateEntityName"),e.exports=r}}),Od=ye({"../../node_modules/strnum/strnum.js"(t,e){var n=/^[-+]?0x[a-fA-F0-9]+$/,r=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var o={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(u,c={}){if(c=Object.assign({},o,c),!u||typeof u!="string")return u;let l=u.trim();if(c.skipLike!==void 0&&c.skipLike.test(l))return u;if(c.hex&&n.test(l))return Number.parseInt(l,16);{let d=r.exec(l);if(d){let p=d[1],g=d[2],m=a(d[3]),R=d[4]||d[6];if(!c.leadingZeros&&g.length>0&&p&&l[2]!==".")return u;if(!c.leadingZeros&&g.length>0&&!p&&l[1]!==".")return u;{let b=Number(l),v=""+b;return v.search(/[eE]/)!==-1||R?c.eNotation?b:u:l.indexOf(".")!==-1?v==="0"&&m===""||v===m||p&&v==="-"+m?b:u:g?m===v||p+m===v?b:u:l===v||l===p+v?b:u}}else return u}}i(s,"toNumber"),D(s,"toNumber");function a(u){return u&&u.indexOf(".")!==-1&&(u=u.replace(/0+$/,""),u==="."?u="0":u[0]==="."?u="0"+u:u[u.length-1]==="."&&(u=u.substr(0,u.length-1))),u}i(a,"trimZeros"),D(a,"trimZeros"),e.exports=s}}),Sd=ye({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var n=Bo(),r=vd(),o=Td(),s=Od(),a=class{static{i(this,"OrderedObjParser")}static{D(this,"OrderedObjParser")}constructor(h){this.options=h,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=u,this.parseXml=g,this.parseTextData=c,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=v,this.replaceEntitiesValue=R,this.readStopNodeData=C,this.saveTextToParentTag=b,this.addChild=m}};function u(h){let w=Object.keys(h);for(let O=0;O<w.length;O++){let M=w[O];this.lastEntities[M]={regex:new RegExp("&"+M+";","g"),val:h[M]}}}i(u,"addExternalEntities"),D(u,"addExternalEntities");function c(h,w,O,M,A,_,B){if(h!==void 0&&(this.options.trimValues&&!M&&(h=h.trim()),h.length>0)){B||(h=this.replaceEntitiesValue(h));let k=this.options.tagValueProcessor(w,h,O,A,_);return k==null?h:typeof k!=typeof h||k!==h?k:this.options.trimValues?U(h,this.options.parseTagValue,this.options.numberParseOptions):h.trim()===h?U(h,this.options.parseTagValue,this.options.numberParseOptions):h}}i(c,"parseTextData"),D(c,"parseTextData");function l(h){if(this.options.removeNSPrefix){let w=h.split(":"),O=h.charAt(0)==="/"?"/":"";if(w[0]==="xmlns")return"";w.length===2&&(h=O+w[1])}return h}i(l,"resolveNameSpace"),D(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(h,w,O){if(!this.options.ignoreAttributes&&typeof h=="string"){let M=n.getAllMatches(h,d),A=M.length,_={};for(let B=0;B<A;B++){let k=this.resolveNameSpace(M[B][1]),N=M[B][4],G=this.options.attributeNamePrefix+k;if(k.length)if(this.options.transformAttributeName&&(G=this.options.transformAttributeName(G)),G==="__proto__"&&(G="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let z=this.options.attributeValueProcessor(k,N,w);z==null?_[G]=N:typeof z!=typeof N||z!==N?_[G]=z:_[G]=U(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[G]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let B={};return B[this.options.attributesGroupName]=_,B}return _}}i(p,"buildAttributesMap"),D(p,"buildAttributesMap");var g=D(function(h){h=h.replace(/\r\n?/g,`
|
|
38
38
|
`);let w=new r("!xml"),O=w,M="",A="";for(let _=0;_<h.length;_++)if(h[_]==="<")if(h[_+1]==="/"){let k=f(h,">",_,"Closing Tag is not closed."),N=h.substring(_+2,k).trim();if(this.options.removeNSPrefix){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&(M=this.saveTextToParentTag(M,O,A));let G=A.substring(A.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let z=0;G&&this.options.unpairedTags.indexOf(G)!==-1?(z=A.lastIndexOf(".",A.lastIndexOf(".")-1),this.tagsNodeStack.pop()):z=A.lastIndexOf("."),A=A.substring(0,z),O=this.tagsNodeStack.pop(),M="",_=k}else if(h[_+1]==="?"){let k=E(h,_,!1,"?>");if(!k)throw new Error("Pi Tag is not closed.");if(M=this.saveTextToParentTag(M,O,A),!(this.options.ignoreDeclaration&&k.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(k.tagName);N.add(this.options.textNodeName,""),k.tagName!==k.tagExp&&k.attrExpPresent&&(N[":@"]=this.buildAttributesMap(k.tagExp,A,k.tagName)),this.addChild(O,N,A)}_=k.closeIndex+1}else if(h.substr(_+1,3)==="!--"){let k=f(h,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=h.substring(_+4,k-2);M=this.saveTextToParentTag(M,O,A),O.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=k}else if(h.substr(_+1,2)==="!D"){let k=o(h,_);this.docTypeEntities=k.entities,_=k.i}else if(h.substr(_+1,2)==="!["){let k=f(h,"]]>",_,"CDATA is not closed.")-2,N=h.substring(_+9,k);M=this.saveTextToParentTag(M,O,A);let G=this.parseTextData(N,O.tagname,A,!0,!1,!0,!0);G==null&&(G=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):O.add(this.options.textNodeName,G),_=k+2}else{let k=E(h,_,this.options.removeNSPrefix),N=k.tagName,G=k.rawTagName,z=k.tagExp,de=k.attrExpPresent,zo=k.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),O&&M&&O.tagname!=="!xml"&&(M=this.saveTextToParentTag(M,O,A,!1));let Vo=O;if(Vo&&this.options.unpairedTags.indexOf(Vo.tagname)!==-1&&(O=this.tagsNodeStack.pop(),A=A.substring(0,A.lastIndexOf("."))),N!==w.tagname&&(A+=A?"."+N:N),this.isItStopNode(this.options.stopNodes,A,N)){let ce="";if(z.length>0&&z.lastIndexOf("/")===z.length-1)_=k.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=k.closeIndex;else{let nr=this.readStopNodeData(h,G,zo+1);if(!nr)throw new Error(`Unexpected end of ${G}`);_=nr.i,ce=nr.tagContent}let tr=new r(N);N!==z&&de&&(tr[":@"]=this.buildAttributesMap(z,A,N)),ce&&(ce=this.parseTextData(ce,N,A,!0,de,!0,!0)),A=A.substr(0,A.lastIndexOf(".")),tr.add(this.options.textNodeName,ce),this.addChild(O,tr,A)}else{if(z.length>0&&z.lastIndexOf("/")===z.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),A=A.substr(0,A.length-1),z=N):z=z.substr(0,z.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let ce=new r(N);N!==z&&de&&(ce[":@"]=this.buildAttributesMap(z,A,N)),this.addChild(O,ce,A),A=A.substr(0,A.lastIndexOf("."))}else{let ce=new r(N);this.tagsNodeStack.push(O),N!==z&&de&&(ce[":@"]=this.buildAttributesMap(z,A,N)),this.addChild(O,ce,A),O=ce}M="",_=zo}}else M+=h[_];return w.child},"parseXml");function m(h,w,O){let M=this.options.updateTag(w.tagname,O,w[":@"]);M===!1||(typeof M=="string"&&(w.tagname=M),h.addChild(w))}i(m,"addChild"),D(m,"addChild");var R=D(function(h){if(this.options.processEntities){for(let w in this.docTypeEntities){let O=this.docTypeEntities[w];h=h.replace(O.regx,O.val)}for(let w in this.lastEntities){let O=this.lastEntities[w];h=h.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let w in this.htmlEntities){let O=this.htmlEntities[w];h=h.replace(O.regex,O.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function b(h,w,O,M){return h&&(M===void 0&&(M=Object.keys(w.child).length===0),h=this.parseTextData(h,w.tagname,O,!1,w[":@"]?Object.keys(w[":@"]).length!==0:!1,M),h!==void 0&&h!==""&&w.add(this.options.textNodeName,h),h=""),h}i(b,"saveTextToParentTag"),D(b,"saveTextToParentTag");function v(h,w,O){let M="*."+O;for(let A in h){let _=h[A];if(M===_||w===_)return!0}return!1}i(v,"isItStopNode"),D(v,"isItStopNode");function S(h,w,O=">"){let M,A="";for(let _=w;_<h.length;_++){let B=h[_];if(M)B===M&&(M="");else if(B==='"'||B==="'")M=B;else if(B===O[0])if(O[1]){if(h[_+1]===O[1])return{data:A,index:_}}else return{data:A,index:_};else B===" "&&(B=" ");A+=B}}i(S,"tagExpWithClosingIndex"),D(S,"tagExpWithClosingIndex");function f(h,w,O,M){let A=h.indexOf(w,O);if(A===-1)throw new Error(M);return A+w.length-1}i(f,"findClosingIndex"),D(f,"findClosingIndex");function E(h,w,O,M=">"){let A=S(h,w+1,M);if(!A)return;let _=A.data,B=A.index,k=_.search(/\s/),N=_,G=!0;k!==-1&&(N=_.substring(0,k),_=_.substring(k+1).trimStart());let z=N;if(O){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1),G=N!==A.data.substr(de+1))}return{tagName:N,tagExp:_,closeIndex:B,attrExpPresent:G,rawTagName:z}}i(E,"readTagExp"),D(E,"readTagExp");function C(h,w,O){let M=O,A=1;for(;O<h.length;O++)if(h[O]==="<")if(h[O+1]==="/"){let _=f(h,">",O,`${w} is not closed`);if(h.substring(O+2,_).trim()===w&&(A--,A===0))return{tagContent:h.substring(M,O),i:_};O=_}else if(h[O+1]==="?")O=f(h,"?>",O+1,"StopNode is not closed.");else if(h.substr(O+1,3)==="!--")O=f(h,"-->",O+3,"StopNode is not closed.");else if(h.substr(O+1,2)==="![")O=f(h,"]]>",O,"StopNode is not closed.")-2;else{let _=E(h,O,">");_&&((_&&_.tagName)===w&&_.tagExp[_.tagExp.length-1]!=="/"&&A++,O=_.closeIndex)}}i(C,"readStopNodeData"),D(C,"readStopNodeData");function U(h,w,O){if(w&&typeof h=="string"){let M=h.trim();return M==="true"?!0:M==="false"?!1:s(h,O)}else return n.isExist(h)?h:""}i(U,"parseValue"),D(U,"parseValue"),e.exports=a}}),Cd=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}i(e,"prettify"),D(e,"prettify");function n(a,u,c){let l,d={};for(let p=0;p<a.length;p++){let g=a[p],m=r(g),R="";if(c===void 0?R=m:R=c+"."+m,m===u.textNodeName)l===void 0?l=g[m]:l+=""+g[m];else{if(m===void 0)continue;if(g[m]){let b=n(g[m],u,R),v=s(b,u);g[":@"]?o(b,g[":@"],R,u):Object.keys(b).length===1&&b[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?b=b[u.textNodeName]:Object.keys(b).length===0&&(u.alwaysCreateTextNode?b[u.textNodeName]="":b=""),d[m]!==void 0&&d.hasOwnProperty(m)?(Array.isArray(d[m])||(d[m]=[d[m]]),d[m].push(b)):u.isArray(m,R,v)?d[m]=[b]:d[m]=b}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}i(n,"compress"),D(n,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}i(r,"propName"),D(r,"propName");function o(a,u,c,l){if(u){let d=Object.keys(u),p=d.length;for(let g=0;g<p;g++){let m=d[g];l.isArray(m,c+"."+m,!0,!0)?a[m]=[u[m]]:a[m]=u[m]}}}i(o,"assignAttributes"),D(o,"assignAttributes");function s(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}i(s,"isLeafTag"),D(s,"isLeafTag"),t.prettify=e}}),Ad=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=xd(),r=Sd(),{prettify:o}=Cd(),s=gu(),a=class{static{i(this,"XMLParser2")}static{D(this,"XMLParser")}constructor(u){this.externalEntities={},this.options=n(u)}parse(u,c){if(typeof u!="string")if(u.toString)u=u.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(c){c===!0&&(c={});let p=s.validate(u,c);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new r(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(u);return this.options.preserveOrder||d===void 0?d:o(d,this.options)}addEntity(u,c){if(c.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(u.indexOf("&")!==-1||u.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(c==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[u]=c}};e.exports=a}}),Ld=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let g=i(m=>{if(u.inlineCharacterLimit===void 0)return m;let R=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return R.length<=u.inlineCharacterLimit?R:m.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
60
60
|
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Zi(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let m="["+p.newline+a.map((R,b)=>{let v=a.length-1===b?p.newline:","+p.newlineOrSpace,S=s(R,u,c+d,l+1);return u.transform&&(S=u.transform(a,b,S)),p.indent+S+v}).join("")+p.pad+"]";return r.pop(),g(m)}if(He(a)){let m=qi(a);if(u.filter&&(m=m.filter(b=>u.filter?.(a,b))),m.length===0)return"{}";r.push(a);let R="{"+p.newline+m.map((b,v)=>{let S=m.length-1===v?p.newline:","+p.newlineOrSpace,f=typeof b=="symbol",E=!f&&/^[a-z$_][$\w]*$/i.test(b),C=f||E?b:s(b,u,"",l+1),U=s(a[b],u,c+d,l+1);return u.transform&&(U=u.transform(a,b,U)),p.indent+String(C)+": "+U+S}).join("")+p.pad+"}";return r.pop(),g(R)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
|
|
61
61
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}i(Xt,"stringifyObject");function _e(t){return t.map(e=>oe(e))}i(_e,"makeErrorsSerializable");function Ke(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:xe(oe(e))}i(Ke,"extractBestMessage");function os(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ht(n))if(n.stack)e.push(n.stack);else{let r=Xt(oe(n));e.push(r)}else if(typeof n=="object"){let r=Xt(n);e.push(r)}else{let r=Br(n);e.push(r)}}),e.join(`
|
|
62
|
-
`)}i(os,"messagesToMultilineText");function xe(t){return typeof t=="string"?t:JSON.stringify(t)}i(xe,"stringifyNonString");function Br(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"?Cr(t):"unknown"}i(Br,"stringifyNonStringToText");var en=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 s=await o;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function we({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new en.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(we,"getTokenFromGcpServiceAccount");async function is(t,e,n){return ss(t,{token:e,returnSecureToken:!0},n)}i(is,"exchangeFirebaseJwtForIdToken");async function tn(t,e,n){return ss(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(tn,"exchangeGgpJwtForIdToken");async function ss(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ss,"fetchToken");var ae=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,en.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 nn=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Pt(this.options)}},il="https://logging.googleapis.com/v2/entries:write?alt=json",jr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Pt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=I.instance.loggingEnvironmentType,this.#i=I.instance.loggingEnvironmentStage,this.#r=I.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:_e(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:jr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Ke(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ae.init(this.#e));let n=await we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(il,{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 q("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(t){let e={allMessages:_e(t.messages)},n="zuplo-production",r=Ke(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:jr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(on,"gcpLogFormat");var Et=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var sn=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new It(this.options)}},zr="__ddtags",Vr="__ddattr",Gr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),sl=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Gr(r)):n.push(`${Gr(r)}:${Gr(o.toString())}`)}),n.join(",")},"formatTags"),It=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=I.instance.loggingEnvironmentType,this.#o=I.instance.loggingEnvironmentStage,this.#n=I.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[zr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(m=>m[zr]!==void 0);a>-1&&(Object.assign(r,s[a][zr]),s.splice(a,1));let u={},c=n.custom[Vr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[Vr]!==void 0);l>-1&&(Object.assign(u,s[l][Vr]),s.splice(l,1));let d=_e(s),g={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ke(d),service:e.loggingId,ddtags:sl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),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 q("data-dog-transport",10,this.dispatchFunction)};var xt=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var al=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:_e(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":I.instance.systemUserAgent,"zp-dn":I.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{i(this,"RemoteLogTransport")}constructor(e){an||(an=new q("remote-log-transport",1,al(e)))}log(e,n){an.enqueue(e),n.waitUntil(an.waitUntilFlushed())}};var ul={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},as=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:ul[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var cl=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=as(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":I.instance.systemUserAgent,"zp-dn":I.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{i(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new q("unified-log-transport",1,cl(e)))}async log(e,n){cn.enqueue(e),n.waitUntil(cn.waitUntilFlushed())}};var Wr=(0,us.debug)("zuplo:logging"),dn=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(I.instance,e),r=await t.setupUserCoreLogger(I.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Wr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(bt);return s?o.push(new xt(s.logger,e.logFormat)):e.isDeno&&o.push(new Et(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new ln({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 wt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Wr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(bt);if(a&&a.captureUserLogs===!0?r.push(new xt(a.logger,e.logFormat)):e.isDeno&&r.push(new Et(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({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 Pt({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 It({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ae.forEach(u=>{u instanceof Y&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new wt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){Wr("Gateway.createRequestLoggers");let a=new Qt(r,o,s),u=new Rt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Rt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var $e=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Jr=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ye=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Kr=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},Qe=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof $e||e instanceof W))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Jr(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Kr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:n});if(u!==null)return new Ye(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ye(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Yr;function cs(t){Yr=t}i(cs,"setGlobalZuploEventContext");function pn(){if(Yr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Yr}i(pn,"getGlobalZuploEventContext");function ls({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:n}){let r=new Headers(t);if(e){for(let[o]of t){let s=o.substring(0,3);li.includes(s.toLowerCase())&&!di.includes(o.toLowerCase())&&r.delete(o)}r.delete(Yo)}else ci.forEach(o=>{r.delete(o)});return n&&pi.forEach(o=>{r.delete(o)}),r}i(ls,"normalizeIncomingRequestHeaders");var Re=(0,ds.debug)("zuplo:runtime"),ll=i(t=>{let e=t.findIndex(n=>n.name===ft.name);return e>-1?[...t.splice(e),ft]:[...t,ft]},"setupSystemNoVersion"),Q=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Re("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o,s){if(Re("Gateway.initialize"),!t.#e){await Ui(s);let a=await dn.init(r),u=e(),c={...u,corsPolicies:ji(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){Re("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=[Yt,Jt,ne];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,n=ll(e.versions),r=new Qe(n);if(e.routes.length===0)return Or(r,this),Mr(r,this),Nr(r,this),zi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(es(r,this),Xi(r,this)),Or(r,this),Mr(r,this),Nr(r,this);for(let s of Ae)s instanceof Ee&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new $e(s);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 y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Re("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Re("Gateway.internalErrorResponse");let o={};if(I.instance.isDeno){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=rs(s.stack)),o={cause:s}}}return T.internalServerError(e,n,{detail:r.message,...o})}async handleRequest(e,n){cs(n);let r=e.headers.get(ze)??e.headers.get(Ko),o=e.headers.get(Me),s=ls({headers:e.headers,removeAllVendorHeadersExceptListed:I.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:I.instance.isDeno});r||(r=crypto.randomUUID(),s.set(ze,r));let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(ir,"true"),a=new Request(a,{headers:S,body:null})}let u={},{userRequestLogger:c,systemRequestLogger:l}=this.#t.createRequestLoggers(r,o,n,u,a),d=new URL(a.url),p=d.pathname,g=this.#n.lookup(a.method,p);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let m=new gn(e.headers),R=new j(a,{params:g.params}),b=new mn({logger:c,route:g.routeConfiguration,requestId:r,event:n,custom:u,incomingRequestProperties:m}),v=te.initialize(b,R);if(g.routeConfiguration===kr&>.value?.notFoundHandler!==void 0){let S=this.#n.lookupByPathOnly(p);v.pathOnlyMatches=S.map(f=>f.routeConfiguration).filter(f=>f instanceof $e)}try{if(F.addLogger(b,l),I.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(d):!d.pathname.startsWith("/__zuplo")){let E=await ki(R,b);if(E instanceof Response)return E;{let C=te.getContextExtensions(b);R=E,C.latestRequest=R}}mt(d)||c.debug(`Request received '${d.pathname}'`,{method:a.method,url:d.pathname,hostname:d.hostname,route:g.routeConfiguration.path});let S=g.executableHandler;dl(S,g,a),Re("Gateway.handleRequest - call user handler");let f=await S(R,b);if(Re("Gateway.handleRequest - user handler"),!(f instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof f}`);if(f.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");if(f.headers.get(ze)===null&&!f.webSocket){let E=new Headers(f.headers);return E.set(ze,r),new Response(f.body,{status:f.status,statusText:f.statusText,headers:E,cf:f.cf})}else return f}catch(S){return Re("Gateway - error executing handler",S),S instanceof L?(c.error(S),l.warn(S)):l.error(S),await this.#i(R,b,S)}}};function dl(t,e,n){if(Re("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(dl,"checkHandler");var ps=i(async(t,e,n)=>{let r=Q.instance.routeData.policies,o=yt([t],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var gn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(dr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(pr)??void 0}get city(){return this.#e.get(sr)??this.#e.get(ri)??void 0}get continent(){return this.#e.get(ar)??this.#e.get(oi)??void 0}get country(){return this.#e.get(ur)??this.#e.get(ii)??void 0}get latitude(){return this.#e.get(lr)??this.#e.get(ai)??void 0}get longitude(){return this.#e.get(cr)??this.#e.get(si)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(ti)??this.#e.get(mr)??void 0}get metroCode(){return this.#e.get(ei)??this.#e.get(fr)??void 0}get region(){return this.#e.get(Qo)??this.#e.get(hr)??void 0}get regionCode(){return this.#e.get(Xo)??this.#e.get(yr)??void 0}get timezone(){return this.#e.get(ni)??this.#e.get(br)??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}}},Ve=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ge=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>ps(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var pl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Qr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!pl.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(Qr,"isRestrictedEnvVariableName");function Xr(t){return!!t.startsWith("ZUPLO_")}i(Xr,"isZuploReadableEnvVariableName");var re=new Proxy({},{get(t,e){if(Qr(String(e))&&!Xr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var ms=ve(Se());var ge=(0,ms.debug)("zuplo:runtime:external-service");function fs(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=I.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(fs,"getServiceAuth");async function hs(t){let e=fs();if(!e)throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.");if(typeof t!="string")throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(I.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let a=I.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await bs(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(hs,"externalServiceTunnelConfig");async function ys(t,e){let n=fs();if(n)if(ge(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(I.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let d=I.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await bs(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);ge(`Calling external service: ${c.toString()}`);let l=await Xe(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ys,"externalServiceHandler");async function bs(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=gl(r);ge(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await gs(`${s}-${o}`),l=await gs(`${s}-${a}-${u}`);return`${c}.${l}`}i(bs,"hashServiceName");async function gs(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(gs,"hashSegment");function gl(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(gl,"sanitizeEnvironmentType");var ws=new Map;ws.set("service:",ys);var Xe=globalThis.fetch;globalThis.fetch=function(t,e){let n=ml(e);if(typeof t=="string"){let r=new URL(t),o=ws.get(r.protocol);return o?o(t,n):Xe(t,n)}else return Xe(t,n)};var ml=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Rs=i(()=>{Q.purgeGatewayCache()},"purgeGatewayCache"),fn=class{constructor(e,n,r,o,s,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=s;this.schemaValidations=a;this.runtimeInit=u}static{i(this,"Handler")}requestHandler=async(e,n)=>{I.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Q.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof y&&(s=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:I.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 Cs=ve(Se());function fl(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(fl,"lexer");function eo(t,e){e===void 0&&(e={});for(var n=fl(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(yl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(h){if(c<n.length&&n[c].type===h)return n[c++].value},"tryConsume"),p=i(function(h){var w=d(h);if(w!==void 0)return w;var O=n[c],M=O.type,A=O.index;throw new TypeError("Unexpected ".concat(M," at ").concat(A,", expected ").concat(h))},"mustConsume"),g=i(function(){for(var h="",w;w=d("CHAR")||d("ESCAPED_CHAR");)h+=w;return h},"consumeText");c<n.length;){var m=d("CHAR"),R=d("NAME"),b=d("PATTERN");if(R||b){var v=m||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:v,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var S=m||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var v=g(),E=d("NAME")||"",C=d("PATTERN")||"",U=g();p("CLOSE"),a.push({name:E||(C?u++:""),pattern:E&&!C?s:C,prefix:v,suffix:U,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(eo,"parse");function Ps(t,e){return hl(eo(t,e),e)}i(Ps,"compile");function hl(t,e){e===void 0&&(e={});var n=bl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",R=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!R)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<g.length;b++){var v=o(g[b],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var v=o(String(g),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!m){var S=R?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}i(hl,"tokensToFunction");function yl(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(yl,"escapeString");function bl(t){return t&&t.sensitive?"":"i"}i(bl,"flags");var vs=ve(Se());var wl=(0,vs.debug)("zuplo:runtime"),no=new TextEncoder,Es={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"},Rl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],et=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new ro(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){wl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},ro=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:g,appendSessionToken:m,allHeaders:R,singleEncode:b}){if(n==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,S;(!c||!l)&&([v,S]=Pl(this.url,this.headers)),this.service=c||v||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=m||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(C=>R||!Rl.includes(C)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(C=>C+":"+(C==="host"?this.url.host:(this.headers.get(C)||"").replace(/\s+/g," "))).join(`
|
|
62
|
+
`)}i(os,"messagesToMultilineText");function xe(t){return typeof t=="string"?t:JSON.stringify(t)}i(xe,"stringifyNonString");function Br(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"?Cr(t):"unknown"}i(Br,"stringifyNonStringToText");var en=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 s=await o;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(ie,"fetchRetry");async function we({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=t;return await new en.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}i(we,"getTokenFromGcpServiceAccount");async function is(t,e,n){return ss(t,{token:e,returnSecureToken:!0},n)}i(is,"exchangeFirebaseJwtForIdToken");async function tn(t,e,n){return ss(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}i(tn,"exchangeGgpJwtForIdToken");async function ss(t,e,n){let r=await ie(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ss,"fetchToken");var ae=class t{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,en.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 nn=class extends Y{constructor(n){super();this.options=n}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Pt(this.options)}},il="https://logging.googleapis.com/v2/entries:write?alt=json",jr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Pt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=I.instance.loggingEnvironmentType,this.#i=I.instance.loggingEnvironmentStage,this.#r=I.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:_e(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:jr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Ke(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ae.init(this.#e));let n=await we({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(il,{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 q("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(t){let e={allMessages:_e(t.messages)},n="zuplo-production",r=Ke(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:jr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}i(on,"gcpLogFormat");var Et=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var sn=class extends Y{constructor(n){super();this.options=n}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new It(this.options)}},zr="__ddtags",Vr="__ddattr",Gr=i(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),sl=i(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Gr(r)):n.push(`${Gr(r)}:${Gr(o.toString())}`)}),n.join(",")},"formatTags"),It=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=I.instance.loggingEnvironmentType,this.#o=I.instance.loggingEnvironmentStage,this.#n=I.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[zr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(m=>m[zr]!==void 0);a>-1&&(Object.assign(r,s[a][zr]),s.splice(a,1));let u={},c=n.custom[Vr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[Vr]!==void 0);l>-1&&(Object.assign(u,s[l][Vr]),s.splice(l,1));let d=_e(s),g={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ke(d),service:e.loggingId,ddtags:sl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),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 q("data-dog-transport",10,this.dispatchFunction)};var xt=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var al=i(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:_e(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":I.instance.systemUserAgent,"zp-dn":I.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{i(this,"RemoteLogTransport")}constructor(e){an||(an=new q("remote-log-transport",1,al(e)))}log(e,n){an.enqueue(e),n.waitUntil(an.waitUntilFlushed())}};var ul={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},as=i((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:ul[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var cl=i(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let s=as(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":I.instance.systemUserAgent,"zp-dn":I.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),cn,ln=class{static{i(this,"UnifiedLogTransport")}constructor(e){cn||(cn=new q("unified-log-transport",1,cl(e)))}async log(e,n){cn.enqueue(e),n.waitUntil(cn.waitUntilFlushed())}};var Wr=(0,us.debug)("zuplo:logging"),dn=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(I.instance,e),r=await t.setupUserCoreLogger(I.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Wr("Gateway.setupSystemCoreLogger");let o=[],s=n.getService(bt);return s?o.push(new xt(s.logger,e.logFormat)):e.isDeno&&o.push(new Et(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new ln({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 wt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Wr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=n.getService(bt);if(a&&a.captureUserLogs===!0?r.push(new xt(a.logger,e.logFormat)):e.isDeno&&r.push(new Et(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new un({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 Pt({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 It({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ae.forEach(u=>{u instanceof Y&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new wt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,n,r,o,s){Wr("Gateway.createRequestLoggers");let a=new Qt(r,o,s),u=new Rt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Rt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var $e=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Jr=class{static{i(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ye=class{static{i(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Kr=class extends Error{static{i(this,"RouterError")}constructor(e,n){super(e,n)}},Qe=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof $e||e instanceof W))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Jr(o,s,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Kr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,n){if(typeof e>"u")throw new y(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:n});if(u!==null)return new Ye(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ye(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Yr;function cs(t){Yr=t}i(cs,"setGlobalZuploEventContext");function pn(){if(Yr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Yr}i(pn,"getGlobalZuploEventContext");function ls({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:n}){let r=new Headers(t);if(e){for(let[o]of t){let s=o.substring(0,3);li.includes(s.toLowerCase())&&!di.includes(o.toLowerCase())&&r.delete(o)}r.delete(Yo)}else ci.forEach(o=>{r.delete(o)});return n&&pi.forEach(o=>{r.delete(o)}),r}i(ls,"normalizeIncomingRequestHeaders");var Re=(0,ds.debug)("zuplo:runtime"),ll=i(t=>{let e=t.findIndex(n=>n.name===ft.name);return e>-1?[...t.splice(e),ft]:[...t,ft]},"setupSystemNoVersion"),Q=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;Re("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,n,r,o,s){if(Re("Gateway.initialize"),!t.#e){await Ui(s);let a=await dn.init(r),u=e(),c={...u,corsPolicies:ji(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){Re("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=[Yt,Jt,ne];#o;setupRoutes=()=>{Re("Gateway.setupRoutes");let e=this.routeData,n=ll(e.versions),r=new Qe(n);if(e.routes.length===0)return Or(r,this),Mr(r,this),Nr(r,this),zi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(es(r,this),Xi(r,this)),Or(r,this),Mr(r,this),Nr(r,this);for(let s of Ae)s instanceof Ee&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new y(`Invalid state - No handler on route for path '${s.path}'`);let u=new J({processors:this.#r,handler:a,gateway:this}),c=new $e(s);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 y("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return Re("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){Re("Gateway.internalErrorResponse");let o={};if(I.instance.isDeno){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=oe(r.cause);"stack"in s&&(s.stack=rs(s.stack)),o={cause:s}}}return T.internalServerError(e,n,{detail:r.message,...o})}async handleRequest(e,n){cs(n);let r=e.headers.get(ze)??e.headers.get(Ko),o=e.headers.get(Me),s=ls({headers:e.headers,removeAllVendorHeadersExceptListed:I.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:I.instance.isDeno});r||(r=crypto.randomUUID(),s.set(ze,r));let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let S=new Headers(a.headers);S.set(ir,"true"),a=new Request(a,{headers:S,body:null})}let u={},{userRequestLogger:c,systemRequestLogger:l}=this.#t.createRequestLoggers(r,o,n,u,a),d=new URL(a.url),p=d.pathname,g=this.#n.lookup(a.method,p);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let m=new gn(e.headers),R=new j(a,{params:g.params}),b=new mn({logger:c,route:g.routeConfiguration,requestId:r,event:n,custom:u,incomingRequestProperties:m}),v=te.initialize(b,R);if(g.routeConfiguration===kr&>.value?.notFoundHandler!==void 0){let S=this.#n.lookupByPathOnly(p);v.pathOnlyMatches=S.map(f=>f.routeConfiguration).filter(f=>f instanceof $e)}try{if(F.addLogger(b,l),I.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(d):!d.pathname.startsWith("/__zuplo")){let E=await ki(R,b);if(E instanceof Response)return E;{let C=te.getContextExtensions(b);R=E,C.latestRequest=R}}mt(d)||c.debug(`Request received '${d.pathname}'`,{method:a.method,url:d.pathname,hostname:d.hostname,route:g.routeConfiguration.path});let S=g.executableHandler;dl(S,g,a),Re("Gateway.handleRequest - call user handler");let f=await S(R,b);if(Re("Gateway.handleRequest - user handler"),!(f instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof f}`);if(f.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");if(f.headers.get(ze)===null&&!f.webSocket){let E=new Headers(f.headers);return E.set(ze,r),new Response(f.body,{status:f.status,statusText:f.statusText,headers:E,cf:f.cf})}else return f}catch(S){return Re("Gateway - error executing handler",S),S instanceof L?(c.error(S),l.warn(S)):l.error(S),await this.#i(R,b,S)}}};function dl(t,e,n){if(Re("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new y(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new y(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}i(dl,"checkHandler");var ps=i(async(t,e,n)=>{let r=Q.instance.routeData.policies,o=yt([t],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var gn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(dr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(pr)??void 0}get city(){return this.#e.get(sr)??this.#e.get(ri)??void 0}get continent(){return this.#e.get(ar)??this.#e.get(oi)??void 0}get country(){return this.#e.get(ur)??this.#e.get(ii)??void 0}get latitude(){return this.#e.get(lr)??this.#e.get(ai)??void 0}get longitude(){return this.#e.get(cr)??this.#e.get(si)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(ti)??this.#e.get(mr)??void 0}get metroCode(){return this.#e.get(ei)??this.#e.get(fr)??void 0}get region(){return this.#e.get(Qo)??this.#e.get(hr)??void 0}get regionCode(){return this.#e.get(Xo)??this.#e.get(yr)??void 0}get timezone(){return this.#e.get(ni)??this.#e.get(br)??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}}},Ve=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ge=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},te=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let s of this.#n)o=await s(e,n,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>ps(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{te.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{te.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var pl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Qr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!pl.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(Qr,"isRestrictedEnvVariableName");function Xr(t){return!!t.startsWith("ZUPLO_")}i(Xr,"isZuploReadableEnvVariableName");var re=new Proxy({},{get(t,e){if(Qr(String(e))&&!Xr(String(e)))return;let n;return globalThis.process?n=globalThis.process.env[e]:n=I.instance.runtime[String(e)],n}});var ms=ve(Se());var ge=(0,ms.debug)("zuplo:runtime:external-service");function fs(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=I.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}i(fs,"getServiceAuth");async function hs(t){let e=fs();if(!e)throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.");if(typeof t!="string")throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[r])s=`https://${e.customServiceMapping[r]}`;else if(I.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let a=I.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await bs(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else s=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:o}}i(hs,"externalServiceTunnelConfig");async function ys(t,e){let n=fs();if(n)if(ge(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),s.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(I.instance.useSha256ServiceRouting){ge("Using sha256 service routing");let d=I.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await bs(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ge("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);ge(`Calling external service: ${c.toString()}`);let l=await Xe(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw ge("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw ge("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ys,"externalServiceHandler");async function bs(t,e,n,r){let o=t.toLowerCase(),s=e.toLowerCase(),a=n.toLowerCase(),u=gl(r);ge(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await gs(`${s}-${o}`),l=await gs(`${s}-${a}-${u}`);return`${c}.${l}`}i(bs,"hashServiceName");async function gs(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(gs,"hashSegment");function gl(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(gl,"sanitizeEnvironmentType");var ws=new Map;ws.set("service:",ys);var Xe=globalThis.fetch;globalThis.fetch=function(t,e){let n=ml(e);if(typeof t=="string"){let r=new URL(t),o=ws.get(r.protocol);return o?o(t,n):Xe(t,n)}else return Xe(t,n)};var ml=i(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Rs=i(()=>{Q.purgeGatewayCache()},"purgeGatewayCache"),fn=class{constructor(e,n,r,o,s,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,n,r)=>{I.initialize(this.buildEnvironment,n);let o;try{o=await Q.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(s){console.error("Error initializing gateway.",s);let a="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";s instanceof y&&(a=s.message);let u={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:a,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:I.instance.isDeno?s.message:void 0};return new Response(JSON.stringify(u,null,2),{status:500,headers:{"content-type":"application/json"}})}return o.handleRequest(e,r)}};var Cs=ve(Se());function fl(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",s=n+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=s;continue}if(r==="("){var u=1,c="",s=n+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){c+=t[s++]+t[s++];continue}if(t[s]===")"){if(u--,u===0){s++;break}}else if(t[s]==="("&&(u++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=t[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=s;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}i(fl,"lexer");function eo(t,e){e===void 0&&(e={});for(var n=fl(t),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(yl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(h){if(c<n.length&&n[c].type===h)return n[c++].value},"tryConsume"),p=i(function(h){var w=d(h);if(w!==void 0)return w;var O=n[c],M=O.type,A=O.index;throw new TypeError("Unexpected ".concat(M," at ").concat(A,", expected ").concat(h))},"mustConsume"),g=i(function(){for(var h="",w;w=d("CHAR")||d("ESCAPED_CHAR");)h+=w;return h},"consumeText");c<n.length;){var m=d("CHAR"),R=d("NAME"),b=d("PATTERN");if(R||b){var v=m||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:R||u++,prefix:v,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var S=m||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var f=d("OPEN");if(f){var v=g(),E=d("NAME")||"",C=d("PATTERN")||"",U=g();p("CLOSE"),a.push({name:E||(C?u++:""),pattern:E&&!C?s:C,prefix:v,suffix:U,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(eo,"parse");function Ps(t,e){return hl(eo(t,e),e)}i(Ps,"compile");function hl(t,e){e===void 0&&(e={});var n=bl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",R=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!R)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<g.length;b++){var v=o(g[b],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var v=o(String(g),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!m){var S=R?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}i(hl,"tokensToFunction");function yl(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(yl,"escapeString");function bl(t){return t&&t.sensitive?"":"i"}i(bl,"flags");var vs=ve(Se());var wl=(0,vs.debug)("zuplo:runtime"),no=new TextEncoder,Es={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"},Rl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],et=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new ro(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){wl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,n),a=fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new y("An unknown error occurred, ensure retries is not negative")}},ro=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:n,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:g,appendSessionToken:m,allHeaders:R,singleEncode:b}){if(n==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,S;(!c||!l)&&([v,S]=Pl(this.url,this.headers)),this.service=c||v||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=m||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(C=>R||!Rl.includes(C)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(C=>C+":"+(C==="host"?this.url.host:(this.headers.get(C)||"").replace(/\s+/g," "))).join(`
|
|
63
63
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!f.has("X-Amz-Expires")&&f.set("X-Amz-Expires","86400"),f.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),f.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=xs(this.encodedPath);let E=new Set;this.encodedSearch=[...this.url.searchParams].filter(([C])=>{if(!C)return!1;if(this.service==="s3"){if(E.has(C))return!1;E.add(C)}return!0}).map(C=>C.map(U=>xs(encodeURIComponent(U)))).sort(([C,U],[h,w])=>C<h?-1:C>h?1:U<w?-1:U>w?1:0).map(C=>C.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await vt("AWS4"+this.secretAccessKey,e),s=await vt(o,this.region),a=await vt(s,this.service);r=await vt(a,"aws4_request"),this.cache.set(n,r)}return to(await vt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,to(await Is(await this.canonicalString()))].join(`
|
|
64
64
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
65
65
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
@@ -74,5 +74,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
74
74
|
`+d}):new Pe(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
75
75
|
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.
|
|
76
76
|
`+l+`
|
|
77
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Gl,"validateComputedSignature");function Wl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Wl,"parseHeader");function Jl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Jl,"secureCompare");async function Kl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Eo[s[u]];return a.join("")}i(Kl,"computeHMACSignatureAsync");var Eo=new Array(256);for(let t=0;t<Eo.length;t++)Eo[t]=t.toString(16).padStart(2,"0");function V(t,e,n="policy"){let r=`${n} '${e}'`;if(!He(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(V,"optionValidator");var rt=class extends pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){V(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Fs(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a}return n.log.error("Error validating stripe webhook",s),T.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Bs(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}i(Bs,"isStripeWebhookEvent");var Tn=class extends Ee{static{i(this,"MeteringPlugin")}};var Yl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new L(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new L(s)}return o}},On=Yl;var Io="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",js="My API Key";async function zs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=I.instance,c=new URL(`/v1/buckets/${t}/consumers`,Io);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:js,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(zs,"createConsumer");async function Vs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=I.instance,u=new URL(`/v1/buckets/${t}/consumers`,Io);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:js,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Vs,"createConsumerInvite");async function Gs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=I.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Io);o.searchParams.set("with-api-key","true");let s=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(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Gs,"deleteConsumer");async function Ws({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=I.instance;if(!We(d))throw new $("No Zuplo JWT token set.");let g=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!g.ok){let m="Error creating monetization subscription.",R;try{R=await g.json()}catch{R={status:g.status,statusText:g.statusText}}throw t.log.error(m,R),new L(m)}t.log.info("Successfully created monetization subscription.",l)}i(Ws,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=I.instance;if(!We(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating monetization subscription with: '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Tt,"updateSubscription");async function Ot({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=I.instance;if(!We(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(c),new L(c)}return u.data[0]}i(Ot,"getSubscription");function Sn(t){return t.replaceAll("_","-")}i(Sn,"stripeStatusToMeteringStatus");async function xo(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 s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{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=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await zs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await On.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Vs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return T.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=Sn(n.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}}),await Ws({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g})}catch(p){return await Gs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{detail:p.message})}return T.ok(t,e)}i(xo,"onCustomerSubscriptionCreated");async function vo(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 s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),T.ok(t,e)}i(vo,"onCustomerSubscriptionDeleted");async function To(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 s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Sn(n.data.object.status);return await Tt({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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await On.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}}),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."})}i(To,"onCustomerSubscriptionUpdated");var Oo=class extends Tn{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!I.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Ql(g))throw new y(`StripeMonetizationPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bs(m))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 '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await xo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await To(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await vo(c,l,m,{meteringBucketId:d});default:return T.badRequest(c,l,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),s=Wi({inboundPolicies:[new rt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});V(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new W({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Ql(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}i(Ql,"isMetricsRegion");var Ks=new WeakMap,Js={},Cn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ks.set(e,n)}};async function Ys(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Je(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ks.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},g=Js[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new q("amberflo-ingest-meter",10,async b=>{try{let v=n.url??"https://app.amberflo.io/ingest",S=await fetch(v,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});S.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${S.status}: ${await S.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),Js[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}i(Ys,"AmberfloMeteringInboundPolicy");async function An(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(An,"sha256");var Qs=new Map;async function X(t,e){let n,r=Qs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await An(JSON.stringify({policyName:t,options:e}))}`,Qs.set(t,n)),n}i(X,"getPolicyCacheName");var Xs="key-metadata-cache-type";function Xl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Xl,"getKeyValue");async function Ln(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(v=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Xl(a,o);if(!u||u==="")return s("No key present");let c=await ed(u),l=await X(r,o),d=new K(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Xs&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${I.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":I.instance.deploymentName??"unknown","User-Agent":I.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),S=JSON.parse(v);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let R=await m.json(),b={isValid:!0,typeId:Xs,user:{sub:R.name,data:R.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(Ln,"ApiKeyInboundPolicy");async function ed(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ed,"hashValue");var ea=Ln;var St=require("jose");var So={},td=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");So[e.jwkUrl]||(So[e.jwkUrl]=(0,St.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,St.jwtVerify)(t,So[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),nd=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,St.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(g=>T.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?td:nd,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let R=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ta=i(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var na=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),m=d.substring(p+1),R=n.accounts.find(b=>b.username===g&&b.password===m);return R||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var rd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function od(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(od,"digestMessage");var id=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await od(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ra(t,e,n,r){let o=await X(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await id(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);rd.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(ra,"CachingInboundPolicy");var oa=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var ia=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var sa=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var aa=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ua=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(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 ca=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,s=yt(n.policies,o?.routeData.policies);return qr(s)(t,e)},"CompositeInboundPolicy");var la=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let s=sd(o);if(!s)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new K(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function sd(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(sd,"getToken");var da=i(async(t,e,n,r)=>(V(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(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 pa=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ot="__unknown__",ga=i(async(t,e,n,r)=>{let o={allow:{countries:st(n.allow?.countries,"allow.countries",r),regionCodes:st(n.allow?.regionCodes,"allow.regionCode",r),asns:st(n.allow?.asns,"allow.asOrganization",r)},block:{countries:st(n.block?.countries,"block.countries",r),regionCodes:st(n.block?.regionCodes,"block.regionCode",r),asns:st(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??ot,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ot,u=e.incomingRequestProperties.asn?.toString()??ot,c=o.ignoreUnknown&&s===ot,l=o.ignoreUnknown&&a===ot,d=o.ignoreUnknown&&u===ot,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return it(t,e,r,s,a,u);let R=o.block.countries,b=o.block.regionCodes,v=o.block.asns;return R.length>0&&R.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?it(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function it(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(it,"blockedResponse");function st(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(st,"toLowerStringArray");var ma=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ha=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Co(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Co(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),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 fa(a[u])}else return a.length>0?fa(a[0]):Co(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 fa(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(fa,"generateResponse");var Co=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var ad="Incoming",ud={logRequestBody:!0,logResponseBody:!0};function ya(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(ya,"headersToObject");function ba(){return new Date().toISOString()}i(ba,"timestamp");var Ao=new WeakMap,cd={};function Pa(t,e){let n=Ao.get(t);n||(n=cd);let r=Object.assign({...n},e);Ao.set(t,r)}i(Pa,"setMoesifContext");async function wa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(wa,"readBody");var ld={},Lo;function Ra(){if(!Lo)throw new L("Invalid State - no _lastLogger");return Lo}i(Ra,"getLastLogger");function dd(t){let e=ld[t];return e||(e=new q("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ra().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Ra().error({status:o.status,body:await o.text()})})),e}i(dd,"getDispatcher");async function Ea(t,e,n,r){Lo=e.log;let o=ba(),s=Object.assign(ud,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await wa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=dd(s.applicationId),d=t.headers.get("true-client-ip"),p=Ao.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ya(t.headers)},m=s.logResponseBody?await wa(u,e):void 0,R={time:ba(),status:u.status,headers:ya(u.headers),body:m},b={request:g,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ad};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(Ea,"MoesifInboundPolicy");async function Ia(t,e,n,r){let o=F.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=I.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(Ia,"loadSubscription");async function xa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=I.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(xa,"consumeSubcriptionQuotas");var pd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function _n(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(_n,"validateMeters");function va(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=qe(t),r=[];for(let o of n)pd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(va,"parseAllowedSubscriptionStatuses");function Ta(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(Ta,"compareMeters");var Nn=class extends pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){_n(n,"setMeters"),le.set(e,Nt,n)}async handler(e,n){V(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Je(this.options.meterOnStatusCodes),s=le.get(n,Nt),a={...this.options.meters,...s};_n(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=va(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,v,S)=>{let f=le.get(S,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let C=le.get(S,Nt),U={...this.options.meters,...C};if(_n(U,this.policyName),o.includes(b.status)&&f&&U){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(U)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=Ta(f.meters,U);if(w&&Object.keys(w).length>0){let O=Object.keys(w);S.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await xa(S,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ia(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),le.set(n,lt,p));let g=le.get(n,lt);if(!g)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(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(b=>!Object.keys(g.meters).includes(b));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(g.meters[b].available<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var Oa=i(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Sa=require("jose");var _o,Ca=i(async(t,e,n,r)=>{if(!_o)try{_o=await(0,Sa.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:_o,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ka=ve(Se());var La=ve(Se());var kn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},No=class extends kn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ko=class extends kn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function gd(t,e){if(Fi(t))throw new No(e)}i(gd,"throwIfUndefinedOrNull");function Ct(t,e){if(gd(t,e),!se(t))throw new ko(e,"string")}i(Ct,"throwIfNotString");var Mn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ct(e,"redisClientUrl"),Ct(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}){Ct(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Dn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var md=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Hn=i(async t=>({key:`ip-${md(t)}`}),"getIP"),Zn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),qn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function $n(t,e){let n;if(Un)return Un;if(I.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Dn,Un=n,n;let{authApiJWT:r,redisURL:o}=I.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=Mn.initialize(o,r,I.instance.deploymentName??"unknown",I.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}i($n,"getRedisClient");async function Fn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(Fn,"getCountAndUpdateExpiry");function Bn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new L(c)}return u},"outerFunction")}i(Bn,"wrapUserFunction");var jn="Retry-After";var Aa=(0,La.debug)("zuplo:policies:RateLimitInboundPolicy"),_a=i(async(t,e,n,r)=>{let o=F.getLogger(e),s=i((h,w)=>{let O={};return(!h||h==="retry-after")&&(O[jn]=w.toString()),T.tooManyRequests(t,e,void 0,O)},"rateLimited"),u={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,g=n.headerMode??"retry-after",m=$n(r,o),b=`bucket/${I.instance.build.BUILD_ID}/${r}/${l}`,v=await X(r,n),S=new K(v,e),f=Fn(b,p,m,o,e.requestId),E;i(async()=>{let h=await f;if(h.count>d){let w=Date.now()+h.ttlSeconds*1e3;S.put(b,w,h.ttlSeconds),Aa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),E=s(g,h.ttlSeconds)}},"asyncCheck")();let U=await S.get(b);if(U!==void 0&&U>Date.now()){Aa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((U-Date.now())/1e3);return s(g,h)}return e.addResponseSendingHook(async h=>E??h),t},"AsyncRateLimitInboundPolicy");var Na=(0,ka.debug)("zuplo:policies:RateLimitInboundPolicy"),fd="strict",Mo=i(async(t,e,n,r)=>{if((n.mode??fd)==="async")return _a(t,e,n,r);let s=Date.now(),a=F.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[jn]=d.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],p=await d(t,e,r),g=p.key,m=p.requestsAllowed??n.requestsAllowed,R=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",v=$n(r,a),f=`bucket/${I.instance.build.BUILD_ID}/${r}/${g}`,E=await Fn(f,R,v,a,e.requestId);return E.count>m?(Na(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(b,E.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;Na(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Do;function Ma(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(Ma,"headersToNameValuePairs");function hd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(hd,"queryToNameValueParis");function yd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(yd,"parseIntOrUndefined");var Da={};async function Ua(t,e,n,r){let o=new Date,s=Date.now();return Do||(Do={name:"zuplo",version:I.instance.build.ZUPLO_VERSION,comment:`zuplo/${I.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:I.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Do,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ma(t.headers),queryString:hd(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ma(a.headers),content:{size:yd(t.headers.get("content-length"))}}}]}}},d=Da[n.apiKey];if(!d){let p=n.apiKey;d=new q("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",R=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Da[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(Ua,"ReadmeMetricsInboundPolicy");var Ha=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Za=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var qa=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var $a=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Fa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ba=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?Fa():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Fa():t},"RequestSizeLimitInboundPolicy");function ja(t,e,n){return`_${ke(t+"_"+e+"_"+n)}`}i(ja,"getRawOperationDataIdentifierName");function zn(t,e,n,r){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(zn,"getIdForParameterSchema");function Vn(t,e,n){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${ke(n.toLowerCase())}`}i(Vn,"getIdForRequestBodySchema");function za(t,e){return`_${ke(t)}__${ke(e)}`}i(za,"getIdForRefSchema");function ke(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(ke,"sanitizedIdentifierName");var at=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),ut=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=zn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=Uo(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),me=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Uo=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Va(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",R,[r],m),he(n.validateBody))return b}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Vn(t.route.path,e.method,o),u=Q.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Uo(l),g=T.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(fe(n.validateBody)&&me(t,n.logLevel??"info",d,[r],p),he(n.validateBody))return g}i(Va,"handleBodyValidation");function Ga(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=at(t),s=ut(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,s.invalidValues,s.errors),he(n.validateHeaders))return u}}i(Ga,"handleHeadersValidation");function Wa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=at(t),o=ut(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}i(Wa,"handlePathParameterValidation");function Ja(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=at(t),o=ut(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}i(Ja,"handleQueryParameterValidation");var Ho=i(async(t,e,n)=>{let r=Ja(e,t,n);if(r!==void 0||(r=Wa(e,t,n),r!==void 0)||(r=Ga(e,t,n),r!==void 0))return r;let o=await Va(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ka=Ho;var Ya=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Qa=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Xa=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var eu=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var tu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var nu=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var bd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ru=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await bd(n.sleepInMs),t},"SleepInboundPolicy");var ou=i(async(t,e,n,r)=>{V(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await ee(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var iu=i(async(t,e,n,r)=>{V(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),s=new K(o,e),a=await s.get(r);if(!a){let u=await wd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function wd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("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 L("Response returned from Azure AD is not in the expected format.")}i(wd,"getAccessToken");var su="https://accounts.google.com/o/oauth2/token",Zo,au=i(async(t,e,n,r)=>{V(n,r).required("serviceAccountJson","string"),Zo||(Zo=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(" ")},s=await X(r,n),a=new K(s,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:Zo,audience:su,payload:o}),l=await tn(su,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 Rd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Pd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],qo,uu=i(async(t,e,n,r)=>{if(V(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Pd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}qo||(qo=await ae.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new K(a,e),c={uid:s,claims:o},l=await An(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:qo,audience:Rd,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await is(g,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $o,cu=i(async(t,e,n,r)=>{V(n,r).required("audience","string").required("serviceAccountJson","string"),$o||($o=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:$o,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var lu="https://www.googleapis.com/oauth2/v4/token",Fo,du=i(async(t,e,n,r)=>{V(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Fo||(Fo=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=qe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(s):a=new K(s,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Fo,audience:lu,payload:o}),l=await tn(lu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("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 pu=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("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 hu=ve(fu());var Gn=class extends Ie{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),V(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Je(e.parseOnStatusCodes):void 0,this.parser=new hu.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Wn=class{static{i(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 Jn=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new q(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Kn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new At(r)),await new At(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new At(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},At=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){pn().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var jo=["sha-1","sha-256","sha-384","sha-512"],Yn=class{static{i(this,"BaseCryptoBeta")}};var Qn=class extends Yn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!jo.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${jo.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 Xn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var er=class extends Xn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new Lt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
77
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Pe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Gl,"validateComputedSignature");function Wl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Wl,"parseHeader");function Jl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Jl,"secureCompare");async function Kl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Eo[s[u]];return a.join("")}i(Kl,"computeHMACSignatureAsync");var Eo=new Array(256);for(let t=0;t<Eo.length;t++)Eo[t]=t.toString(16).padStart(2,"0");function V(t,e,n="policy"){let r=`${n} '${e}'`;if(!He(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(V,"optionValidator");var rt=class extends pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){V(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Fs(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a}return n.log.error("Error validating stripe webhook",s),T.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Bs(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}i(Bs,"isStripeWebhookEvent");var Tn=class extends Ee{static{i(this,"MeteringPlugin")}};var Yl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new L(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new L(s)}return o}},On=Yl;var Io="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",js="My API Key";async function zs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=I.instance,c=new URL(`/v1/buckets/${t}/consumers`,Io);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:js,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,g),new L(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(zs,"createConsumer");async function Vs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=I.instance,u=new URL(`/v1/buckets/${t}/consumers`,Io);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:js,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Vs,"createConsumerInvite");async function Gs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=I.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Io);o.searchParams.set("with-api-key","true");let s=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(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Gs,"deleteConsumer");async function Ws({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=I.instance;if(!We(d))throw new $("No Zuplo JWT token set.");let g=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!g.ok){let m="Error creating monetization subscription.",R;try{R=await g.json()}catch{R={status:g.status,statusText:g.statusText}}throw t.log.error(m,R),new L(m)}t.log.info("Successfully created monetization subscription.",l)}i(Ws,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=I.instance;if(!We(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating monetization subscription with: '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Tt,"updateSubscription");async function Ot({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=I.instance;if(!We(o))throw new $("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new L(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(c),new L(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(c),new L(c)}return u.data[0]}i(Ot,"getSubscription");function Sn(t){return t.replaceAll("_","-")}i(Sn,"stripeStatusToMeteringStatus");async function xo(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 s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),T.badRequest(t,e,{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=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await zs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await On.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Vs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return T.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=Sn(n.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}}),await Ws({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g})}catch(p){return await Gs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.internalServerError(t,e,{detail:p.message})}return T.ok(t,e)}i(xo,"onCustomerSubscriptionCreated");async function vo(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 s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),T.ok(t,e)}i(vo,"onCustomerSubscriptionDeleted");async function To(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 s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),T.badRequest(t,e,{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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Sn(n.data.object.status);return await Tt({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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await On.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}}),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."})}i(To,"onCustomerSubscriptionUpdated");var Oo=class extends Tn{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!I.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Ql(g))throw new y(`StripeMonetizationPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bs(m))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 '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await xo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await To(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await vo(c,l,m,{meteringBucketId:d});default:return T.badRequest(c,l,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),s=Wi({inboundPolicies:[new rt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});V(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new J({processors:[ne,s],handler:o,gateway:r}),u=new W({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Ql(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}i(Ql,"isMetricsRegion");var Ks=new WeakMap,Js={},Cn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Ks.set(e,n)}};async function Ys(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Je(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ks.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new L(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ze(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},g=Js[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new q("amberflo-ingest-meter",10,async b=>{try{let v=n.url??"https://app.amberflo.io/ingest",S=await fetch(v,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});S.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${S.status}: ${await S.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),Js[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}i(Ys,"AmberfloMeteringInboundPolicy");async function An(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(An,"sha256");var Qs=new Map;async function X(t,e){let n,r=Qs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await An(JSON.stringify({policyName:t,options:e}))}`,Qs.set(t,n)),n}i(X,"getPolicyCacheName");var Xs="key-metadata-cache-type";function Xl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Xl,"getKeyValue");async function Ln(t,e,n,r){if(!n.bucketName)if(re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(v=>o.allowUnauthenticatedRequests?t:T.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Xl(a,o);if(!u||u==="")return s("No key present");let c=await ed(u),l=await X(r,o),d=new K(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Xs&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${I.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":I.instance.deploymentName??"unknown","User-Agent":I.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),S=JSON.parse(v);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let R=await m.json(),b={isValid:!0,typeId:Xs,user:{sub:R.name,data:R.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(Ln,"ApiKeyInboundPolicy");async function ed(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ed,"hashValue");var ea=Ln;var St=require("jose");var So={},td=i(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");So[e.jwkUrl]||(So[e.jwkUrl]=(0,St.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,St.jwtVerify)(t,So[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),nd=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,St.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(g=>T.unauthorized(t,e,{detail:g}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?td:nd,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,n)}catch(m){let R=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${R.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ta=i(async(t,e,n,r)=>ee(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var na=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),m=d.substring(p+1),R=n.accounts.find(b=>b.username===g&&b.password===m);return R||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var rd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function od(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(od,"digestMessage");var id=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await od(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ra(t,e,n,r){let o=await X(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await id(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);rd.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(ra,"CachingInboundPolicy");var oa=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var ia=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var sa=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var aa=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ua=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return ee(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 ca=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Q.instance,s=yt(n.policies,o?.routeData.policies);return qr(s)(t,e)},"CompositeInboundPolicy");var la=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return T.unauthorized(t,e,{detail:"No authorization header"});let s=sd(o);if(!s)return T.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new K(a,e),c=await u.get(s);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function sd(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(sd,"getToken");var da=i(async(t,e,n,r)=>(V(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ee(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 pa=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ot="__unknown__",ga=i(async(t,e,n,r)=>{let o={allow:{countries:st(n.allow?.countries,"allow.countries",r),regionCodes:st(n.allow?.regionCodes,"allow.regionCode",r),asns:st(n.allow?.asns,"allow.asOrganization",r)},block:{countries:st(n.block?.countries,"block.countries",r),regionCodes:st(n.block?.regionCodes,"block.regionCode",r),asns:st(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??ot,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ot,u=e.incomingRequestProperties.asn?.toString()??ot,c=o.ignoreUnknown&&s===ot,l=o.ignoreUnknown&&a===ot,d=o.ignoreUnknown&&u===ot,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return it(t,e,r,s,a,u);let R=o.block.countries,b=o.block.regionCodes,v=o.block.asns;return R.length>0&&R.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?it(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function it(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(it,"blockedResponse");function st(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(st,"toLowerStringArray");var ma=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var ha=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Co(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Co(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),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 fa(a[u])}else return a.length>0?fa(a[0]):Co(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 fa(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(fa,"generateResponse");var Co=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return T.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var ad="Incoming",ud={logRequestBody:!0,logResponseBody:!0};function ya(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(ya,"headersToObject");function ba(){return new Date().toISOString()}i(ba,"timestamp");var Ao=new WeakMap,cd={};function Pa(t,e){let n=Ao.get(t);n||(n=cd);let r=Object.assign({...n},e);Ao.set(t,r)}i(Pa,"setMoesifContext");async function wa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(wa,"readBody");var ld={},Lo;function Ra(){if(!Lo)throw new L("Invalid State - no _lastLogger");return Lo}i(Ra,"getLastLogger");function dd(t){let e=ld[t];return e||(e=new q("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ra().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Ra().error({status:o.status,body:await o.text()})})),e}i(dd,"getDispatcher");async function Ea(t,e,n,r){Lo=e.log;let o=ba(),s=Object.assign(ud,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await wa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=dd(s.applicationId),d=t.headers.get("true-client-ip"),p=Ao.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ya(t.headers)},m=s.logResponseBody?await wa(u,e):void 0,R={time:ba(),status:u.status,headers:ya(u.headers),body:m},b={request:g,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ad};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(Ea,"MoesifInboundPolicy");async function Ia(t,e,n,r){let o=F.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=I.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}i(Ia,"loadSubscription");async function xa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=I.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(xa,"consumeSubcriptionQuotas");var pd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function _n(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(_n,"validateMeters");function va(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=qe(t),r=[];for(let o of n)pd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(va,"parseAllowedSubscriptionStatuses");function Ta(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(Ta,"compareMeters");var Nn=class extends pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){_n(n,"setMeters"),le.set(e,Nt,n)}async handler(e,n){V(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Je(this.options.meterOnStatusCodes),s=le.get(n,Nt),a={...this.options.meters,...s};_n(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=va(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,v,S)=>{let f=le.get(S,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let C=le.get(S,Nt),U={...this.options.meters,...C};if(_n(U,this.policyName),o.includes(b.status)&&f&&U){S.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(U)} on response status '${b.status}'`);let{metersInSubscription:h,metersNotInSubscription:w}=Ta(f.meters,U);if(w&&Object.keys(w).length>0){let O=Object.keys(w);S.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${O}'`)}await xa(S,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ia(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:T.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),le.set(n,lt,p));let g=le.get(n,lt);if(!g)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(g&&Object.keys(g.meters).length===0)return n.log.error(`Quota is not set up for subscription '${g.id}'`),T.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(b=>!Object.keys(g.meters).includes(b));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),T.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(g.meters[b].available<=0&&!r)return T.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var Oa=i(async(t,e,n,r)=>ee(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Sa=require("jose");var _o,Ca=i(async(t,e,n,r)=>{if(!_o)try{_o=await(0,Sa.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ee(t,e,{issuer:n.authUrl,secret:_o,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ka=ve(Se());var La=ve(Se());var kn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},No=class extends kn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ko=class extends kn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function gd(t,e){if(Fi(t))throw new No(e)}i(gd,"throwIfUndefinedOrNull");function Ct(t,e){if(gd(t,e),!se(t))throw new ko(e,"string")}i(Ct,"throwIfNotString");var Mn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ct(e,"redisClientUrl"),Ct(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}){Ct(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Dn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ct(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var md=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Hn=i(async t=>({key:`ip-${md(t)}`}),"getIP"),Zn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),qn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function $n(t,e){let n;if(Un)return Un;if(I.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Dn,Un=n,n;let{authApiJWT:r,redisURL:o}=I.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=Mn.initialize(o,r,I.instance.deploymentName??"unknown",I.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}i($n,"getRedisClient");async function Fn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(Fn,"getCountAndUpdateExpiry");function Bn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new L(c)}return u},"outerFunction")}i(Bn,"wrapUserFunction");var jn="Retry-After";var Aa=(0,La.debug)("zuplo:policies:RateLimitInboundPolicy"),_a=i(async(t,e,n,r)=>{let o=F.getLogger(e),s=i((h,w)=>{let O={};return(!h||h==="retry-after")&&(O[jn]=w.toString()),T.tooManyRequests(t,e,void 0,O)},"rateLimited"),u={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,g=n.headerMode??"retry-after",m=$n(r,o),b=`bucket/${I.instance.build.BUILD_ID}/${r}/${l}`,v=await X(r,n),S=new K(v,e),f=Fn(b,p,m,o,e.requestId),E;i(async()=>{let h=await f;if(h.count>d){let w=Date.now()+h.ttlSeconds*1e3;S.put(b,w,h.ttlSeconds),Aa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),E=s(g,h.ttlSeconds)}},"asyncCheck")();let U=await S.get(b);if(U!==void 0&&U>Date.now()){Aa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let h=Math.round((U-Date.now())/1e3);return s(g,h)}return e.addResponseSendingHook(async h=>E??h),t},"AsyncRateLimitInboundPolicy");var Na=(0,ka.debug)("zuplo:policies:RateLimitInboundPolicy"),fd="strict",Mo=i(async(t,e,n,r)=>{if((n.mode??fd)==="async")return _a(t,e,n,r);let s=Date.now(),a=F.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[jn]=d.toString()),T.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Bn(n,r),user:Zn,ip:Hn,all:qn}[n.rateLimitBy],p=await d(t,e,r),g=p.key,m=p.requestsAllowed??n.requestsAllowed,R=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",v=$n(r,a),f=`bucket/${I.instance.build.BUILD_ID}/${r}/${g}`,E=await Fn(f,R,v,a,e.requestId);return E.count>m?(Na(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${f}' (strict mode)`),c(b,E.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;Na(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Do;function Ma(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(Ma,"headersToNameValuePairs");function hd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(hd,"queryToNameValueParis");function yd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(yd,"parseIntOrUndefined");var Da={};async function Ua(t,e,n,r){let o=new Date,s=Date.now();return Do||(Do={name:"zuplo",version:I.instance.build.ZUPLO_VERSION,comment:`zuplo/${I.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:I.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Do,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ma(t.headers),queryString:hd(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ma(a.headers),content:{size:yd(t.headers.get("content-length"))}}}]}}},d=Da[n.apiKey];if(!d){let p=n.apiKey;d=new q("readme-metering-inbound-policy",10,async g=>{try{let m=n.url??"https://metrics.readme.io/request",R=await fetch(m,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});R.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${R.status}: '${await R.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Da[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(Ua,"ReadmeMetricsInboundPolicy");var Ha=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Za=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var qa=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var $a=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Fa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ba=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?Fa():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Fa():t},"RequestSizeLimitInboundPolicy");function ja(t,e,n){return`_${ke(t+"_"+e+"_"+n)}`}i(ja,"getRawOperationDataIdentifierName");function zn(t,e,n,r){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(zn,"getIdForParameterSchema");function Vn(t,e,n){return`_${ke(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${ke(n.toLowerCase())}`}i(Vn,"getIdForRequestBodySchema");function za(t,e){return`_${ke(t)}__${ke(e)}`}i(za,"getIdForRefSchema");function ke(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(ke,"sanitizedIdentifierName");var at=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),ut=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=zn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=Uo(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),me=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Uo=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Va(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let R=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,t,{detail:`${R}, see errors property for more details`,errors:`${m}`});if(fe(n.validateBody)&&me(t,n.logLevel??"info",R,[r],m),he(n.validateBody))return b}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,R=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Vn(t.route.path,e.method,o),u=Q.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=T.badRequest(e,t,{detail:m});return fe(n.validateBody)&&me(t,n.logLevel??"info",m,[r],[m]),he(n.validateBody)?R:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Uo(l),g=T.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(fe(n.validateBody)&&me(t,n.logLevel??"info",d,[r],p),he(n.validateBody))return g}i(Va,"handleBodyValidation");function Ga(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=at(t),s=ut(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,s.invalidValues,s.errors),he(n.validateHeaders))return u}}i(Ga,"handleHeadersValidation");function Wa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=at(t),o=ut(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}i(Wa,"handlePathParameterValidation");function Ja(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=at(t),o=ut(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",s,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}i(Ja,"handleQueryParameterValidation");var Ho=i(async(t,e,n)=>{let r=Ja(e,t,n);if(r!==void 0||(r=Wa(e,t,n),r!==void 0)||(r=Ga(e,t,n),r!==void 0))return r;let o=await Va(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ka=Ho;var Ya=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return T.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Qa=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Xa=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var eu=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var tu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var nu=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var bd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ru=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await bd(n.sleepInMs),t},"SleepInboundPolicy");var ou=i(async(t,e,n,r)=>{V(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await ee(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var iu=i(async(t,e,n,r)=>{V(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),s=new K(o,e),a=await s.get(r);if(!a){let u=await wd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function wd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("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 L("Response returned from Azure AD is not in the expected format.")}i(wd,"getAccessToken");var su="https://accounts.google.com/o/oauth2/token",Zo,au=i(async(t,e,n,r)=>{V(n,r).required("serviceAccountJson","string"),Zo||(Zo=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(" ")},s=await X(r,n),a=new K(s,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:Zo,audience:su,payload:o}),l=await tn(su,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 Rd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Pd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],qo,uu=i(async(t,e,n,r)=>{if(V(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Pd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}qo||(qo=await ae.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new L(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new K(a,e),c={uid:s,claims:o},l=await An(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:qo,audience:Rd,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await is(g,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new L("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var $o,cu=i(async(t,e,n,r)=>{V(n,r).required("audience","string").required("serviceAccountJson","string"),$o||($o=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:$o,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var lu="https://www.googleapis.com/oauth2/v4/token",Fo,du=i(async(t,e,n,r)=>{V(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Fo||(Fo=await ae.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=qe(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(s):a=new K(s,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Fo,audience:lu,payload:o}),l=await tn(lu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("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 pu=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return T.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("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 hu=ve(fu());var Gn=class extends Ie{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),V(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Je(e.parseOnStatusCodes):void 0,this.parser=new hu.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Wn=class{static{i(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 Jn=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new q(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),pn().waitUntil(this.#e.waitUntilFlushed())}};var Kn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new At(r)),await new At(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new At(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},At=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){pn().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var jo=["sha-1","sha-256","sha-384","sha-512"],Yn=class{static{i(this,"BaseCryptoBeta")}};var Qn=class extends Yn{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!jo.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${jo.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 Xn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var er=class extends Xn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=I.instance.runtime.ZUPLO_KV;if(!n)throw new Lt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
78
78
|
/*! For license information please see index.minified.js.LEGAL.txt */
|