@zuplo/runtime 5.1823.0 → 5.1825.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +4 -4
- package/index.minified.js +3 -3
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -3700,19 +3700,19 @@ export declare interface SleepInboundPolicyOptions {
|
|
|
3700
3700
|
/* Excluded from this release type: StandardEnv */
|
|
3701
3701
|
|
|
3702
3702
|
/**
|
|
3703
|
-
* Adds stripe
|
|
3703
|
+
* Adds stripe monetization routes and configuration
|
|
3704
3704
|
* @beta
|
|
3705
3705
|
*/
|
|
3706
|
-
export declare class
|
|
3706
|
+
export declare class StripeMonetizationPlugin extends MeteringPlugin {
|
|
3707
3707
|
private options;
|
|
3708
|
-
constructor(options:
|
|
3708
|
+
constructor(options: StripeMonetizationPluginOptions);
|
|
3709
3709
|
registerRoutes(router: Router, gateway: Gateway): void;
|
|
3710
3710
|
}
|
|
3711
3711
|
|
|
3712
3712
|
/**
|
|
3713
3713
|
* @beta
|
|
3714
3714
|
*/
|
|
3715
|
-
export declare interface
|
|
3715
|
+
export declare interface StripeMonetizationPluginOptions {
|
|
3716
3716
|
/**
|
|
3717
3717
|
* Stripe Webhook settings
|
|
3718
3718
|
*/
|
package/index.minified.js
CHANGED
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
`);let b=new r("!xml"),S=b,k="",C="";for(let _=0;_<h.length;_++)if(h[_]==="<")if(h[_+1]==="/"){let M=f(h,">",_,"Closing Tag is not closed."),N=h.substring(_+2,M).trim();if(this.options.removeNSPrefix){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&(k=this.saveTextToParentTag(k,S,C));let G=C.substring(C.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let V=0;G&&this.options.unpairedTags.indexOf(G)!==-1?(V=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):V=C.lastIndexOf("."),C=C.substring(0,V),S=this.tagsNodeStack.pop(),k="",_=M}else if(h[_+1]==="?"){let M=E(h,_,!1,"?>");if(!M)throw new Error("Pi Tag is not closed.");if(k=this.saveTextToParentTag(k,S,C),!(this.options.ignoreDeclaration&&M.tagName==="?xml"||this.options.ignorePiTags)){let N=new r(M.tagName);N.add(this.options.textNodeName,""),M.tagName!==M.tagExp&&M.attrExpPresent&&(N[":@"]=this.buildAttributesMap(M.tagExp,C,M.tagName)),this.addChild(S,N,C)}_=M.closeIndex+1}else if(h.substr(_+1,3)==="!--"){let M=f(h,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=h.substring(_+4,M-2);k=this.saveTextToParentTag(k,S,C),S.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=M}else if(h.substr(_+1,2)==="!D"){let M=o(h,_);this.docTypeEntities=M.entities,_=M.i}else if(h.substr(_+1,2)==="!["){let M=f(h,"]]>",_,"CDATA is not closed.")-2,N=h.substring(_+9,M);k=this.saveTextToParentTag(k,S,C);let G=this.parseTextData(N,S.tagname,C,!0,!1,!0,!0);G==null&&(G=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):S.add(this.options.textNodeName,G),_=M+2}else{let M=E(h,_,this.options.removeNSPrefix),N=M.tagName,G=M.rawTagName,V=M.tagExp,de=M.attrExpPresent,No=M.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),S&&k&&S.tagname!=="!xml"&&(k=this.saveTextToParentTag(k,S,C,!1));let ko=S;if(ko&&this.options.unpairedTags.indexOf(ko.tagname)!==-1&&(S=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),N!==b.tagname&&(C+=C?"."+N:N),this.isItStopNode(this.options.stopNodes,C,N)){let ce="";if(V.length>0&&V.lastIndexOf("/")===V.length-1)_=M.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=M.closeIndex;else{let zn=this.readStopNodeData(h,G,No+1);if(!zn)throw new Error(`Unexpected end of ${G}`);_=zn.i,ce=zn.tagContent}let Vn=new r(N);N!==V&&de&&(Vn[":@"]=this.buildAttributesMap(V,C,N)),ce&&(ce=this.parseTextData(ce,N,C,!0,de,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),Vn.add(this.options.textNodeName,ce),this.addChild(S,Vn,C)}else{if(V.length>0&&V.lastIndexOf("/")===V.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),C=C.substr(0,C.length-1),V=N):V=V.substr(0,V.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let ce=new r(N);N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),C=C.substr(0,C.lastIndexOf("."))}else{let ce=new r(N);this.tagsNodeStack.push(S),N!==V&&de&&(ce[":@"]=this.buildAttributesMap(V,C,N)),this.addChild(S,ce,C),S=ce}k="",_=No}}else k+=h[_];return b.child},"parseXml");function m(h,b,S){let k=this.options.updateTag(b.tagname,S,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),h.addChild(b))}s(m,"addChild"),U(m,"addChild");var R=U(function(h){if(this.options.processEntities){for(let b in this.docTypeEntities){let S=this.docTypeEntities[b];h=h.replace(S.regx,S.val)}for(let b in this.lastEntities){let S=this.lastEntities[b];h=h.replace(S.regex,S.val)}if(this.options.htmlEntities)for(let b in this.htmlEntities){let S=this.htmlEntities[b];h=h.replace(S.regex,S.val)}h=h.replace(this.ampEntity.regex,this.ampEntity.val)}return h},"replaceEntitiesValue");function w(h,b,S,k){return h&&(k===void 0&&(k=Object.keys(b.child).length===0),h=this.parseTextData(h,b.tagname,S,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,k),h!==void 0&&h!==""&&b.add(this.options.textNodeName,h),h=""),h}s(w,"saveTextToParentTag"),U(w,"saveTextToParentTag");function I(h,b,S){let k="*."+S;for(let C in h){let _=h[C];if(k===_||b===_)return!0}return!1}s(I,"isItStopNode"),U(I,"isItStopNode");function T(h,b,S=">"){let k,C="";for(let _=b;_<h.length;_++){let $=h[_];if(k)$===k&&(k="");else if($==='"'||$==="'")k=$;else if($===S[0])if(S[1]){if(h[_+1]===S[1])return{data:C,index:_}}else return{data:C,index:_};else $===" "&&($=" ");C+=$}}s(T,"tagExpWithClosingIndex"),U(T,"tagExpWithClosingIndex");function f(h,b,S,k){let C=h.indexOf(b,S);if(C===-1)throw new Error(k);return C+b.length-1}s(f,"findClosingIndex"),U(f,"findClosingIndex");function E(h,b,S,k=">"){let C=T(h,b+1,k);if(!C)return;let _=C.data,$=C.index,M=_.search(/\s/),N=_,G=!0;M!==-1&&(N=_.substring(0,M),_=_.substring(M+1).trimStart());let V=N;if(S){let de=N.indexOf(":");de!==-1&&(N=N.substr(de+1),G=N!==C.data.substr(de+1))}return{tagName:N,tagExp:_,closeIndex:$,attrExpPresent:G,rawTagName:V}}s(E,"readTagExp"),U(E,"readTagExp");function A(h,b,S){let k=S,C=1;for(;S<h.length;S++)if(h[S]==="<")if(h[S+1]==="/"){let _=f(h,">",S,`${b} is not closed`);if(h.substring(S+2,_).trim()===b&&(C--,C===0))return{tagContent:h.substring(k,S),i:_};S=_}else if(h[S+1]==="?")S=f(h,"?>",S+1,"StopNode is not closed.");else if(h.substr(S+1,3)==="!--")S=f(h,"-->",S+3,"StopNode is not closed.");else if(h.substr(S+1,2)==="![")S=f(h,"]]>",S,"StopNode is not closed.")-2;else{let _=E(h,S,">");_&&((_&&_.tagName)===b&&_.tagExp[_.tagExp.length-1]!=="/"&&C++,S=_.closeIndex)}}s(A,"readStopNodeData"),U(A,"readStopNodeData");function Z(h,b,S){if(b&&typeof h=="string"){let k=h.trim();return k==="true"?!0:k==="false"?!1:i(h,S)}else return n.isExist(h)?h:""}s(Z,"parseValue"),U(Z,"parseValue"),e.exports=a}}),ld=ye({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,u){return n(a,u)}s(e,"prettify"),U(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 w=n(g[m],u,R),I=i(w,u);g[":@"]?o(w,g[":@"],R,u):Object.keys(w).length===1&&w[u.textNodeName]!==void 0&&!u.alwaysCreateTextNode?w=w[u.textNodeName]:Object.keys(w).length===0&&(u.alwaysCreateTextNode?w[u.textNodeName]="":w=""),d[m]!==void 0&&d.hasOwnProperty(m)?(Array.isArray(d[m])||(d[m]=[d[m]]),d[m].push(w)):u.isArray(m,R,I)?d[m]=[w]:d[m]=w}}}return typeof l=="string"?l.length>0&&(d[u.textNodeName]=l):l!==void 0&&(d[u.textNodeName]=l),d}s(n,"compress"),U(n,"compress");function r(a){let u=Object.keys(a);for(let c=0;c<u.length;c++){let l=u[c];if(l!==":@")return l}}s(r,"propName"),U(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]}}}s(o,"assignAttributes"),U(o,"assignAttributes");function i(a,u){let{textNodeName:c}=u,l=Object.keys(a).length;return!!(l===0||l===1&&(a[c]||typeof a[c]=="boolean"||a[c]===0))}s(i,"isLeafTag"),U(i,"isLeafTag"),t.prettify=e}}),dd=ye({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:n}=id(),r=cd(),{prettify:o}=ld(),i=Fa(),a=class{static{s(this,"XMLParser2")}static{U(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=i.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}}),pd=ye({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var n=`
|
|
39
39
|
`;function r(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=n),o(l,d,"",p)}s(r,"toXml"),U(r,"toXml");function o(l,d,p,g){let m="",R=!1;for(let w=0;w<l.length;w++){let I=l[w],T=i(I);if(T===void 0)continue;let f="";if(p.length===0?f=T:f=`${p}.${T}`,T===d.textNodeName){let b=I[T];u(f,d)||(b=d.tagValueProcessor(T,b),b=c(b,d)),R&&(m+=g),m+=b,R=!1;continue}else if(T===d.cdataPropName){R&&(m+=g),m+=`<![CDATA[${I[T][0][d.textNodeName]}]]>`,R=!1;continue}else if(T===d.commentPropName){m+=g+`<!--${I[T][0][d.textNodeName]}-->`,R=!0;continue}else if(T[0]==="?"){let b=a(I[":@"],d),S=T==="?xml"?"":g,k=I[T][0][d.textNodeName];k=k.length!==0?" "+k:"",m+=S+`<${T}${k}${b}?>`,R=!0;continue}let E=g;E!==""&&(E+=d.indentBy);let A=a(I[":@"],d),Z=g+`<${T}${A}`,h=o(I[T],d,f,E);d.unpairedTags.indexOf(T)!==-1?d.suppressUnpairedNode?m+=Z+">":m+=Z+"/>":(!h||h.length===0)&&d.suppressEmptyNode?m+=Z+"/>":h&&h.endsWith(">")?m+=Z+`>${h}${g}</${T}>`:(m+=Z+">",h&&g!==""&&(h.includes("/>")||h.includes("</"))?m+=g+d.indentBy+h+g:m+=h,m+=`</${T}>`),R=!0}return m}s(o,"arrToStr"),U(o,"arrToStr");function i(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let g=d[p];if(l.hasOwnProperty(g)&&g!==":@")return g}}s(i,"propName"),U(i,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let g in l){if(!l.hasOwnProperty(g))continue;let m=d.attributeValueProcessor(g,l[g]);m=c(m,d),m===!0&&d.suppressBooleanAttributes?p+=` ${g.substr(d.attributeNamePrefix.length)}`:p+=` ${g.substr(d.attributeNamePrefix.length)}="${m}"`}return p}s(a,"attr_to_str"),U(a,"attr_to_str");function u(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let g in d.stopNodes)if(d.stopNodes[g]===l||d.stopNodes[g]==="*."+p)return!0;return!1}s(u,"isStopNode"),U(u,"isStopNode");function c(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let g=d.entities[p];l=l.replace(g.regex,g.val)}return l}s(c,"replaceEntitiesValue"),U(c,"replaceEntitiesValue"),e.exports=r}}),gd=ye({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var n=pd(),r={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(c,l){return l},attributeValueProcessor:function(c,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function o(c){this.options=Object.assign({},r,c),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=u),this.processTextOrObjNode=i,this.options.format?(this.indentate=a,this.tagEndChar=`>
|
|
40
40
|
`,this.newLine=`
|
|
41
|
-
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?n(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let g in c)if(Object.prototype.hasOwnProperty.call(c,g))if(typeof c[g]>"u")this.isAttribute(g)&&(p+="");else if(c[g]===null)this.isAttribute(g)?p+="":g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar;else if(c[g]instanceof Date)p+=this.buildTextValNode(c[g],g,"",l);else if(typeof c[g]!="object"){let m=this.isAttribute(g);if(m)d+=this.buildAttrPairStr(m,""+c[g]);else if(g===this.options.textNodeName){let R=this.options.tagValueProcessor(g,""+c[g]);p+=this.replaceEntitiesValue(R)}else p+=this.buildTextValNode(c[g],g,"",l)}else if(Array.isArray(c[g])){let m=c[g].length,R="";for(let w=0;w<m;w++){let I=c[g][w];typeof I>"u"||(I===null?g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?R+=this.j2x(I,l+1).val:R+=this.processTextOrObjNode(I,g,l):R+=this.buildTextValNode(I,g,"",l))}this.options.oneListGroup&&(R=this.buildObjectNode(R,g,"",l)),p+=R}else if(this.options.attributesGroupName&&g===this.options.attributesGroupName){let m=Object.keys(c[g]),R=m.length;for(let w=0;w<R;w++)d+=this.buildAttrPairStr(m[w],""+c[g][m[w]])}else p+=this.processTextOrObjNode(c[g],g,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function i(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}s(i,"processTextOrObjNode"),U(i,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let g="</"+l+this.tagEndChar,m="";return l[0]==="?"&&(m="?",g=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+m+">"+c+g:this.options.commentPropName!==!1&&l===this.options.commentPropName&&m.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+m+this.tagEndChar+c+this.indentate(p)+g}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let g=this.options.tagValueProcessor(l,c);return g=this.replaceEntitiesValue(g),g===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+g+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),md=Fa(),fd=dd(),hd=gd();Ba.exports={XMLParser:fd,XMLValidator:md,XMLBuilder:hd};});var yd={};Ya(yd,{API_KEY:()=>Ui,AWSLoggingPlugin:()=>wn,AmberfloMeteringInboundPolicy:()=>Cs,AmberfloMeteringPolicy:()=>Sn,ApiAuthKeyInboundPolicy:()=>_s,ApiKeyInboundPolicy:()=>Cn,AuditLogDataStaxProvider:()=>En,AuditLogPlugin:()=>In,Auth0JwtInboundPolicy:()=>Ns,AwsLambdaHandlerExtensions:()=>ls,BasicAuthInboundPolicy:()=>ks,BasicRateLimitInboundPolicy:()=>Io,CachingInboundPolicy:()=>Ms,ChangeMethodInboundPolicy:()=>Us,ClearHeadersInboundPolicy:()=>Hs,ClearHeadersOutboundPolicy:()=>Ds,ClerkJwtInboundPolicy:()=>Zs,CognitoJwtInboundPolicy:()=>qs,CompositeInboundPolicy:()=>$s,ConfigurationError:()=>y,ContentTypes:()=>$t,ContextData:()=>le,CryptoBeta:()=>Fn,CurityPhantomTokenInboundPolicy:()=>Fs,DataDogLoggingPlugin:()=>on,DataDogMetricsPlugin:()=>Rn,DynaTraceLoggingPlugin:()=>fn,DynatraceMetricsPlugin:()=>Pn,FirebaseJwtInboundPolicy:()=>Bs,FormDataToJsonInboundPolicy:()=>js,GeoFilterInboundPolicy:()=>Vs,GoogleCloudLoggingPlugin:()=>tn,Handler:()=>gn,HttpProblems:()=>O,HttpStatusCode:()=>jt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>zs,KeyValueStore:()=>jn,LokiLoggingPlugin:()=>hn,LookupResult:()=>Ke,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>Ws,MoesifInboundPolicy:()=>ea,MonetizationInboundPolicy:()=>Ln,OktaJwtInboundPolicy:()=>ia,OpenIdJwtInboundPolicy:()=>ee,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>Oe,PropelAuthJwtInboundPolicy:()=>aa,RateLimitInboundPolicy:()=>Io,ReadmeMetricsInboundPolicy:()=>pa,RemoveHeadersInboundPolicy:()=>ga,RemoveHeadersOutboundPolicy:()=>ma,RemoveQueryParamsInboundPolicy:()=>fa,ReplaceStringOutboundPolicy:()=>ha,RequestSizeLimitInboundPolicy:()=>ba,RequestValidationInboundPolicy:()=>To,RequireOriginInboundPolicy:()=>Ta,ResponseSendingEvent:()=>Ve,ResponseSentEvent:()=>ze,Router:()=>Ye,RuntimeError:()=>L,SYSTEM_LOGGER:()=>bt,SchemaBasedRequestValidation:()=>va,ServiceProviderImpl:()=>qn,SetBodyInboundPolicy:()=>Sa,SetHeadersInboundPolicy:()=>Oa,SetHeadersOutboundPolicy:()=>Ca,SetQueryParamsInboundPolicy:()=>Aa,SetStatusOutboundPolicy:()=>La,SleepInboundPolicy:()=>_a,StripeMeteringPlugin:()=>fo,StripeWebhookVerificationInboundPolicy:()=>nt,SumoLogicLoggingPlugin:()=>yn,SupabaseJwtInboundPolicy:()=>Na,SystemLogMap:()=>F,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>ka,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ua,UpstreamFirebaseUserAuthInboundPolicy:()=>Ha,UpstreamGcpJwtInboundPolicy:()=>Da,UpstreamGcpServiceAuthInboundPolicy:()=>qa,VMWareLogInsightLoggingPlugin:()=>bn,ValidateJsonSchemaInbound:()=>$a,XmlToJsonOutboundPolicy:()=>Zn,ZoneCache:()=>ve,ZuploRequest:()=>j,awsLambdaHandler:()=>ds,environment:()=>re,getIdForParameterSchema:()=>Hn,getIdForRefSchema:()=>Ra,getIdForRequestBodySchema:()=>Dn,getRawOperationDataIdentifierName:()=>wa,httpStatuses:()=>Vt,isRestrictedEnvVariableName:()=>qr,isZuploReadableEnvVariableName:()=>$r,openApiSpecHandler:()=>ps,originalFetch:()=>Qe,purgeGatewayCache:()=>Xi,redirectHandler:()=>gs,sanitizedIdentifierName:()=>Ne,serialize:()=>Ft,setMoesifContext:()=>Xs,urlForwardHandler:()=>ms,urlRewriteHandler:()=>fs,webSocketHandler:()=>hs,webSocketPipelineHandler:()=>ws});module.exports=Qa(yd);var q=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},L=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends L{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},At=class extends L{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var x=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new q("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var Lt=globalThis,Uo=Lt.caches;if(Uo){let t=Uo.open;Lt.caches.open=function(e){let n=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Lt.caches.default,Object.freeze(Lt.caches)}var Ho=new Map,Gn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Be=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Ho.get(e);r||(r=new Gn(n),Ho.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Wn="__zuplo-expiry-header",ve=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(Wn);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Wn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(Wn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Be(r),this.#n=new ve(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Do="zuplo-request-id",ct="zp-rid",Zo="zp-body-removed",je="cf-ray",Jn="cf-ipcity",Kn="cf-ipcontinent",Yn="cf-ipcountry",Qn="cf-iplongitude",Xn="cf-iplatitude",qo="zp-ipcity",$o="zp-ipcontinent",Fo="zp-ipcountry",Bo="zp-iplongitude",jo="zp-iplatitude",Vo="true-client-ip",er="zp-asn",tr="zp-asorg",nr="zp-colo",rr="zp-postalcode",or="zp-metrocode",ir="zp-region",sr="zp-regioncode",ar="zp-timezone",zo=[Jn,Kn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar],Go=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],lt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",_t="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var ji=ke(Ue());var pt=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new L("Error in custom 'problemResponseFormat'",{cause:i})}})}},Oe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await pt.problemResponseFormat(e,n,r)}};function Zt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Zt(n)}return Object.freeze(t)}s(Zt,"deepFreeze");var j=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Zt(this.#e)}get params(){return Zt(this.#t)}user};var He=class{static{s(this,"RuntimePlugin")}},Ee=class extends He{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},gt={},Ce=[],pi=[],gi=[],mi=[];var qt={addPlugin(t){Ce.push(t)},addRequestHook(t){pi.push(t)},addResponseSendingHook(t){gi.push(t)},addResponseSendingFinalHook(t){mi.push(t)}},fi=s(async(t,e)=>{let n=t;for(let r of pi){let o=await r(n,e);if(o instanceof j)n=o;else{if(o instanceof Response)return o;throw new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),hi=s(async(t,e,n)=>{let r=t;for(let o of gi){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),yi=s(async(t,e,n)=>{for(let r of mi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function bi(t=()=>Promise.resolve()){await t(qt),gt.value=qt;for(let e of Ce)e instanceof Ee&&await e.initialize(qt);pt.setProblemResponseFormat(qt.problemResponseFormat)}s(bi,"initializeRuntime");var $t={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Ft(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith($t.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith($t.Json)||!e?JSON.stringify(t):t}s(Ft,"serialize");function mt(t){return Q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(mt,"isSystemRoute");var J=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async w=>{let I=a.pop();return I?I(o,i,n,u):await this.#e(async f=>{let E=await r(f,i);return ic(E)},n)(w,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ve(o,l);i.dispatchEvent(p);let g=te.getContextExtensions(i),m=g.latestRequest,R;try{R=await p.mutableResponse}catch(w){return i.log.error(w),n.errorHandler(o,i,w)}try{R=await g.onResponseSending(R,m,i)}catch(w){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,i,w)}try{R=await hi(R,m,i)}catch(w){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,i,w)}i.dispatchEvent(new ze(o,R));try{await g.onResponseSendingFinal(l,m,i)}catch(w){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}try{await yi(l,m,i)}catch(w){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}return R}};function ic(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Ft(t),{headers:{"content-type":"application/json"}})}s(ic,"resultToResponse");var Ae=class extends He{static{s(this,"MetricsPlugin")}};var F=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new q(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var B=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Bt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=x.instance.loggingId,this.#e=e,this.#t=new B("ellie-metrics-transport",10,this.dispatchFunction,F.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=x.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":x.instance.deploymentName??"unknown","user-agent":x.instance.systemUserAgent}});if(!u.ok){let c=await u.text();F.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var W=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ft={name:"__system-no-version",pathPrefix:""};var ne=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(Vo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof W&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new Bt(e)),Ce.forEach(R=>{if(R instanceof Ae){let w=R.getTransport();m.push(w)}}),m.forEach(R=>{R.pushMetrics(g,e)}),a},"metricsProcessor");var be=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(be||{});var hr=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return O.notFound(i,a);let l=x.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&F.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var jt=(P=>(P[P.CONTINUE=100]="CONTINUE",P[P.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",P[P.PROCESSING=102]="PROCESSING",P[P.EARLY_HINTS=103]="EARLY_HINTS",P[P.OK=200]="OK",P[P.CREATED=201]="CREATED",P[P.ACCEPTED=202]="ACCEPTED",P[P.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",P[P.NO_CONTENT=204]="NO_CONTENT",P[P.RESET_CONTENT=205]="RESET_CONTENT",P[P.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",P[P.MULTI_STATUS=207]="MULTI_STATUS",P[P.ALREADY_REPORTED=208]="ALREADY_REPORTED",P[P.IM_USED=226]="IM_USED",P[P.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",P[P.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",P[P.FOUND=302]="FOUND",P[P.SEE_OTHER=303]="SEE_OTHER",P[P.NOT_MODIFIED=304]="NOT_MODIFIED",P[P.USE_PROXY=305]="USE_PROXY",P[P.SWITCH_PROXY=306]="SWITCH_PROXY",P[P.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",P[P.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",P[P.BAD_REQUEST=400]="BAD_REQUEST",P[P.UNAUTHORIZED=401]="UNAUTHORIZED",P[P.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",P[P.FORBIDDEN=403]="FORBIDDEN",P[P.NOT_FOUND=404]="NOT_FOUND",P[P.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",P[P.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",P[P.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",P[P.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",P[P.CONFLICT=409]="CONFLICT",P[P.GONE=410]="GONE",P[P.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",P[P.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",P[P.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",P[P.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",P[P.URI_TOO_LONG=414]="URI_TOO_LONG",P[P.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",P[P.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",P[P.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",P[P.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",P[P.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",P[P.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",P[P.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",P[P.LOCKED=423]="LOCKED",P[P.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",P[P.TOO_EARLY=425]="TOO_EARLY",P[P.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",P[P.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",P[P.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",P[P.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",P[P.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",P[P.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",P[P.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",P[P.BAD_GATEWAY=502]="BAD_GATEWAY",P[P.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",P[P.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",P[P.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",P[P.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",P[P.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",P[P.LOOP_DETECTED=508]="LOOP_DETECTED",P[P.NOT_EXTENDED=510]="NOT_EXTENDED",P[P.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",P))(jt||{}),wi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var sc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Vt=sc;function ac(t){return`${new URL(t.url).pathname}`}s(ac,"instance");function uc(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}s(uc,"trace");var cc=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:ac(e),trace:uc(e,n),...r},additionalHeaders:o,statusText:Vt[t.status]}),"merge"),yr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?Oe.format(e,n,r):Oe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:wi[e],...n}}},O=class extends yr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=cc(this.getProblemFromStatus(e),n,r,o,i);return Oe.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:lc}=Object.prototype,{propertyIsEnumerable:dc}=Object.prototype;function br(t){return lc.call(t)}s(br,"toString");function se(t){return typeof t=="string"}s(se,"isString");function Ge(t){return se(t)&&t!==""}s(Ge,"isNonEmptyString");function Ri(t){return br(t)==="[object RegExp]"}s(Ri,"isRegexp");function Pi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>dc.call(t,e))]}s(Pi,"getOwnEnumerableKeys");function De(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(De,"isObject");function wr(t){return typeof t=="number"&&!isNaN(t)}s(wr,"isNumber");function Rr(t){return t===!0||t===!1}s(Rr,"isBoolean");function Ei(t){return typeof t>"u"}s(Ei,"isUndefined");function Ii(t){return Ei(t)||t===null}s(Ii,"isUndefinedOrNull");function ht(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ht,"isErrorLike");var xi=new Map;function We(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=xi.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return xi.set(t,r),r}s(We,"statusCodesStringToNumberArray");function Ze(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new L(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ze,"getValueFromRequestUser");function qe(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}s(qe,"parseValueToStringArray");function vi(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!De(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!wr(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Rr(n.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Pr(n,"allowedHeaders"),o=Pr(n,"allowedMethods"),i=Pr(n,"exposeHeaders"),a;try{a=qe(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(vi,"parseCorsPolicies");function Pr(t,e){let n;if(t[e]!==void 0)try{n=qe(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Pr,"parseOptionalProperty");var zt=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Gt=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Er=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return O.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=t.lookup(l,c);if(!g)return O.notFound(a,u);let m=g.routeConfiguration,R=pc(l,d,p,m,n);return R.isValid?new Response(void 0,{status:200,statusText:"OK",headers:R.headers}):(R.error&&u.log.warn(R.error),O.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),i=new W({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),pc=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=zt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Ti=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Ir=new W({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Si=s((t,e)=>{let n=s(async(o,i)=>{let a=gt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return O.notFound(o,i)},"notFoundHandler"),r=new J({processors:[ne],handler:n,gateway:e});t.addRoute(Ir,r.execute)},"registerNotMatchedHandler");var gc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Oi=s(t=>{gc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Oi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=mc(o,n.routeData.corsPolicies),u=fc(t,a),c=new Headers(i.headers);return Oi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),mc=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),fc=s((t,e)=>{let n=zt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var xr=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Wt],handler:n,gateway:e}),o=new W({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Jt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new L(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},pe=class extends Jt{static{s(this,"InboundPolicy")}},Ie=class extends Jt{static{s(this,"OutboundPolicy")}};var Sr=class extends pe{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Or=class extends Ie{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},vr=new Map;function yt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!vr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Sr(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);vr.set(a.name,c)}),n.map(i=>{let a=vr.get(i);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}s(yt,"getInboundPolicyInstances");var Tr=new Map;function hc(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Tr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ie)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Or(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Tr.set(i.name,u)}),n.map(o=>{let i=Tr.get(o);if(i===void 0)throw new L("Internal error. Policy not found in cache.");return i})}s(hc,"getOutboundPolicyInstances");var Cr=s(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n);if(u instanceof j)i=u;else if(u instanceof Request)i=new j(u);else{if(u instanceof Response)return u;throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),yc=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Kt=s(async(t,e,n,r)=>{let o=yt(e.route,n.routeData.policies),i=hc(e.route,n.routeData.policies);return Ai({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Ci({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ai({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ci,"createInternalPolicyProcessor");async function Ai({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Cr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=yc(r),d;return x.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Ai,"executePolicyProcessor");function Li(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||bc,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=wc(l,o)}i=u+1}return n}s(Li,"parse");function bc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(bc,"decode");function wc(t,e){try{return e(t)}catch{return t}}s(wc,"tryDecode");function _i(t,e){try{let n=/v\d+(-\d+)?/g,o=Li(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(_i,"devPortalBaseURL");var Ni="/__zuplo/dev-portal",Rc="dev-portal-id",Pc="dev-portal-host",Ec="zp-account",Ic="zp-project",xc="dev-portal-build",vc=`
|
|
41
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}s(o,"Builder"),U(o,"Builder"),o.prototype.build=function(c){return this.options.preserveOrder?n(c,this.options):(Array.isArray(c)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(c={[this.options.arrayNodeName]:c}),this.j2x(c,0).val)},o.prototype.j2x=function(c,l){let d="",p="";for(let g in c)if(Object.prototype.hasOwnProperty.call(c,g))if(typeof c[g]>"u")this.isAttribute(g)&&(p+="");else if(c[g]===null)this.isAttribute(g)?p+="":g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar;else if(c[g]instanceof Date)p+=this.buildTextValNode(c[g],g,"",l);else if(typeof c[g]!="object"){let m=this.isAttribute(g);if(m)d+=this.buildAttrPairStr(m,""+c[g]);else if(g===this.options.textNodeName){let R=this.options.tagValueProcessor(g,""+c[g]);p+=this.replaceEntitiesValue(R)}else p+=this.buildTextValNode(c[g],g,"",l)}else if(Array.isArray(c[g])){let m=c[g].length,R="";for(let w=0;w<m;w++){let I=c[g][w];typeof I>"u"||(I===null?g[0]==="?"?p+=this.indentate(l)+"<"+g+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+g+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?R+=this.j2x(I,l+1).val:R+=this.processTextOrObjNode(I,g,l):R+=this.buildTextValNode(I,g,"",l))}this.options.oneListGroup&&(R=this.buildObjectNode(R,g,"",l)),p+=R}else if(this.options.attributesGroupName&&g===this.options.attributesGroupName){let m=Object.keys(c[g]),R=m.length;for(let w=0;w<R;w++)d+=this.buildAttrPairStr(m[w],""+c[g][m[w]])}else p+=this.processTextOrObjNode(c[g],g,l);return{attrStr:d,val:p}},o.prototype.buildAttrPairStr=function(c,l){return l=this.options.attributeValueProcessor(c,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+c:" "+c+'="'+l+'"'};function i(c,l,d){let p=this.j2x(c,d+1);return c[this.options.textNodeName]!==void 0&&Object.keys(c).length===1?this.buildTextValNode(c[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}s(i,"processTextOrObjNode"),U(i,"processTextOrObjNode"),o.prototype.buildObjectNode=function(c,l,d,p){if(c==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let g="</"+l+this.tagEndChar,m="";return l[0]==="?"&&(m="?",g=""),(d||d==="")&&c.indexOf("<")===-1?this.indentate(p)+"<"+l+d+m+">"+c+g:this.options.commentPropName!==!1&&l===this.options.commentPropName&&m.length===0?this.indentate(p)+`<!--${c}-->`+this.newLine:this.indentate(p)+"<"+l+d+m+this.tagEndChar+c+this.indentate(p)+g}},o.prototype.closeTag=function(c){let l="";return this.options.unpairedTags.indexOf(c)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${c}`,l},o.prototype.buildTextValNode=function(c,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${c}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${c}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let g=this.options.tagValueProcessor(l,c);return g=this.replaceEntitiesValue(g),g===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+g+"</"+l+this.tagEndChar}},o.prototype.replaceEntitiesValue=function(c){if(c&&c.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];c=c.replace(d.regex,d.val)}return c};function a(c){return this.options.indentBy.repeat(c)}s(a,"indentate"),U(a,"indentate");function u(c){return c.startsWith(this.options.attributeNamePrefix)&&c!==this.options.textNodeName?c.substr(this.attrPrefixLen):!1}s(u,"isAttribute"),U(u,"isAttribute"),e.exports=o}}),md=Fa(),fd=dd(),hd=gd();Ba.exports={XMLParser:fd,XMLValidator:md,XMLBuilder:hd};});var yd={};Ya(yd,{API_KEY:()=>Ui,AWSLoggingPlugin:()=>wn,AmberfloMeteringInboundPolicy:()=>Cs,AmberfloMeteringPolicy:()=>Sn,ApiAuthKeyInboundPolicy:()=>_s,ApiKeyInboundPolicy:()=>Cn,AuditLogDataStaxProvider:()=>En,AuditLogPlugin:()=>In,Auth0JwtInboundPolicy:()=>Ns,AwsLambdaHandlerExtensions:()=>ls,BasicAuthInboundPolicy:()=>ks,BasicRateLimitInboundPolicy:()=>Io,CachingInboundPolicy:()=>Ms,ChangeMethodInboundPolicy:()=>Us,ClearHeadersInboundPolicy:()=>Hs,ClearHeadersOutboundPolicy:()=>Ds,ClerkJwtInboundPolicy:()=>Zs,CognitoJwtInboundPolicy:()=>qs,CompositeInboundPolicy:()=>$s,ConfigurationError:()=>y,ContentTypes:()=>$t,ContextData:()=>le,CryptoBeta:()=>Fn,CurityPhantomTokenInboundPolicy:()=>Fs,DataDogLoggingPlugin:()=>on,DataDogMetricsPlugin:()=>Rn,DynaTraceLoggingPlugin:()=>fn,DynatraceMetricsPlugin:()=>Pn,FirebaseJwtInboundPolicy:()=>Bs,FormDataToJsonInboundPolicy:()=>js,GeoFilterInboundPolicy:()=>Vs,GoogleCloudLoggingPlugin:()=>tn,Handler:()=>gn,HttpProblems:()=>O,HttpStatusCode:()=>jt,InboundPolicy:()=>pe,JWTScopeValidationInboundPolicy:()=>zs,KeyValueStore:()=>jn,LokiLoggingPlugin:()=>hn,LookupResult:()=>Ke,MemoryZoneReadThroughCache:()=>Y,MockApiInboundPolicy:()=>Ws,MoesifInboundPolicy:()=>ea,MonetizationInboundPolicy:()=>Ln,OktaJwtInboundPolicy:()=>ia,OpenIdJwtInboundPolicy:()=>ee,OutboundPolicy:()=>Ie,ProblemResponseFormatter:()=>Oe,PropelAuthJwtInboundPolicy:()=>aa,RateLimitInboundPolicy:()=>Io,ReadmeMetricsInboundPolicy:()=>pa,RemoveHeadersInboundPolicy:()=>ga,RemoveHeadersOutboundPolicy:()=>ma,RemoveQueryParamsInboundPolicy:()=>fa,ReplaceStringOutboundPolicy:()=>ha,RequestSizeLimitInboundPolicy:()=>ba,RequestValidationInboundPolicy:()=>To,RequireOriginInboundPolicy:()=>Ta,ResponseSendingEvent:()=>Ve,ResponseSentEvent:()=>ze,Router:()=>Ye,RuntimeError:()=>L,SYSTEM_LOGGER:()=>bt,SchemaBasedRequestValidation:()=>va,ServiceProviderImpl:()=>qn,SetBodyInboundPolicy:()=>Sa,SetHeadersInboundPolicy:()=>Oa,SetHeadersOutboundPolicy:()=>Ca,SetQueryParamsInboundPolicy:()=>Aa,SetStatusOutboundPolicy:()=>La,SleepInboundPolicy:()=>_a,StripeMonetizationPlugin:()=>fo,StripeWebhookVerificationInboundPolicy:()=>nt,SumoLogicLoggingPlugin:()=>yn,SupabaseJwtInboundPolicy:()=>Na,SystemLogMap:()=>F,SystemRouteName:()=>be,UpstreamAzureAdServiceAuthInboundPolicy:()=>ka,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ua,UpstreamFirebaseUserAuthInboundPolicy:()=>Ha,UpstreamGcpJwtInboundPolicy:()=>Da,UpstreamGcpServiceAuthInboundPolicy:()=>qa,VMWareLogInsightLoggingPlugin:()=>bn,ValidateJsonSchemaInbound:()=>$a,XmlToJsonOutboundPolicy:()=>Zn,ZoneCache:()=>ve,ZuploRequest:()=>j,awsLambdaHandler:()=>ds,environment:()=>re,getIdForParameterSchema:()=>Hn,getIdForRefSchema:()=>Ra,getIdForRequestBodySchema:()=>Dn,getRawOperationDataIdentifierName:()=>wa,httpStatuses:()=>Vt,isRestrictedEnvVariableName:()=>qr,isZuploReadableEnvVariableName:()=>$r,openApiSpecHandler:()=>ps,originalFetch:()=>Qe,purgeGatewayCache:()=>Xi,redirectHandler:()=>gs,sanitizedIdentifierName:()=>Ne,serialize:()=>Ft,setMoesifContext:()=>Xs,urlForwardHandler:()=>ms,urlRewriteHandler:()=>fs,webSocketHandler:()=>hs,webSocketPipelineHandler:()=>ws});module.exports=Qa(yd);var q=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},L=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},y=class extends L{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},At=class extends L{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var x=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new q("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var Lt=globalThis,Uo=Lt.caches;if(Uo){let t=Uo.open;Lt.caches.open=function(e){let n=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Lt.caches.default,Object.freeze(Lt.caches)}var Ho=new Map,Gn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Be=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Ho.get(e);r||(r=new Gn(n),Ho.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Wn="__zuplo-expiry-header",ve=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(Wn);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Wn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(Wn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var Y=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Be(r),this.#n=new ve(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Do="zuplo-request-id",ct="zp-rid",Zo="zp-body-removed",je="cf-ray",Jn="cf-ipcity",Kn="cf-ipcontinent",Yn="cf-ipcountry",Qn="cf-iplongitude",Xn="cf-iplatitude",qo="zp-ipcity",$o="zp-ipcontinent",Fo="zp-ipcountry",Bo="zp-iplongitude",jo="zp-iplatitude",Vo="true-client-ip",er="zp-asn",tr="zp-asorg",nr="zp-colo",rr="zp-postalcode",or="zp-metrocode",ir="zp-region",sr="zp-regioncode",ar="zp-timezone",zo=[Jn,Kn,Yn,Qn,Xn,er,tr,nr,rr,or,ir,sr,ar],Go=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],lt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",_t="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var ji=ke(Ue());var pt=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new L("Error in custom 'problemResponseFormat'",{cause:i})}})}},Oe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await pt.problemResponseFormat(e,n,r)}};function Zt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Zt(n)}return Object.freeze(t)}s(Zt,"deepFreeze");var j=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Zt(this.#e)}get params(){return Zt(this.#t)}user};var He=class{static{s(this,"RuntimePlugin")}},Ee=class extends He{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},gt={},Ce=[],pi=[],gi=[],mi=[];var qt={addPlugin(t){Ce.push(t)},addRequestHook(t){pi.push(t)},addResponseSendingHook(t){gi.push(t)},addResponseSendingFinalHook(t){mi.push(t)}},fi=s(async(t,e)=>{let n=t;for(let r of pi){let o=await r(n,e);if(o instanceof j)n=o;else{if(o instanceof Response)return o;throw new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),hi=s(async(t,e,n)=>{let r=t;for(let o of gi){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),yi=s(async(t,e,n)=>{for(let r of mi)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function bi(t=()=>Promise.resolve()){await t(qt),gt.value=qt;for(let e of Ce)e instanceof Ee&&await e.initialize(qt);pt.setProblemResponseFormat(qt.problemResponseFormat)}s(bi,"initializeRuntime");var $t={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Ft(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith($t.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith($t.Json)||!e?JSON.stringify(t):t}s(Ft,"serialize");function mt(t){return Q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(mt,"isSystemRoute");var J=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async w=>{let I=a.pop();return I?I(o,i,n,u):await this.#e(async f=>{let E=await r(f,i);return ic(E)},n)(w,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ve(o,l);i.dispatchEvent(p);let g=te.getContextExtensions(i),m=g.latestRequest,R;try{R=await p.mutableResponse}catch(w){return i.log.error(w),n.errorHandler(o,i,w)}try{R=await g.onResponseSending(R,m,i)}catch(w){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,i,w)}try{R=await hi(R,m,i)}catch(w){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${w.message}'`,w),n.errorHandler(o,i,w)}i.dispatchEvent(new ze(o,R));try{await g.onResponseSendingFinal(l,m,i)}catch(w){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}try{await yi(l,m,i)}catch(w){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${w.message}'`,w),w}return R}};function ic(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Ft(t),{headers:{"content-type":"application/json"}})}s(ic,"resultToResponse");var Ae=class extends He{static{s(this,"MetricsPlugin")}};var F=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new q(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var B=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Bt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=x.instance.loggingId,this.#e=e,this.#t=new B("ellie-metrics-transport",10,this.dispatchFunction,F.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=x.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":x.instance.deploymentName??"unknown","user-agent":x.instance.systemUserAgent}});if(!u.ok){let c=await u.text();F.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var W=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},ft={name:"__system-no-version",pathPrefix:""};var ne=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(je)??void 0,c=t.headers.get(Vo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof W&&(d=e.route.systemRouteName);let p=te.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new Bt(e)),Ce.forEach(R=>{if(R instanceof Ae){let w=R.getTransport();m.push(w)}}),m.forEach(R=>{R.pushMetrics(g,e)}),a},"metricsProcessor");var be=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(be||{});var hr=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return O.notFound(i,a);let l=x.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&F.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var jt=(P=>(P[P.CONTINUE=100]="CONTINUE",P[P.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",P[P.PROCESSING=102]="PROCESSING",P[P.EARLY_HINTS=103]="EARLY_HINTS",P[P.OK=200]="OK",P[P.CREATED=201]="CREATED",P[P.ACCEPTED=202]="ACCEPTED",P[P.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",P[P.NO_CONTENT=204]="NO_CONTENT",P[P.RESET_CONTENT=205]="RESET_CONTENT",P[P.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",P[P.MULTI_STATUS=207]="MULTI_STATUS",P[P.ALREADY_REPORTED=208]="ALREADY_REPORTED",P[P.IM_USED=226]="IM_USED",P[P.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",P[P.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",P[P.FOUND=302]="FOUND",P[P.SEE_OTHER=303]="SEE_OTHER",P[P.NOT_MODIFIED=304]="NOT_MODIFIED",P[P.USE_PROXY=305]="USE_PROXY",P[P.SWITCH_PROXY=306]="SWITCH_PROXY",P[P.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",P[P.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",P[P.BAD_REQUEST=400]="BAD_REQUEST",P[P.UNAUTHORIZED=401]="UNAUTHORIZED",P[P.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",P[P.FORBIDDEN=403]="FORBIDDEN",P[P.NOT_FOUND=404]="NOT_FOUND",P[P.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",P[P.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",P[P.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",P[P.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",P[P.CONFLICT=409]="CONFLICT",P[P.GONE=410]="GONE",P[P.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",P[P.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",P[P.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",P[P.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",P[P.URI_TOO_LONG=414]="URI_TOO_LONG",P[P.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",P[P.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",P[P.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",P[P.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",P[P.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",P[P.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",P[P.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",P[P.LOCKED=423]="LOCKED",P[P.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",P[P.TOO_EARLY=425]="TOO_EARLY",P[P.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",P[P.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",P[P.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",P[P.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",P[P.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",P[P.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",P[P.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",P[P.BAD_GATEWAY=502]="BAD_GATEWAY",P[P.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",P[P.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",P[P.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",P[P.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",P[P.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",P[P.LOOP_DETECTED=508]="LOOP_DETECTED",P[P.NOT_EXTENDED=510]="NOT_EXTENDED",P[P.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",P))(jt||{}),wi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var sc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Vt=sc;function ac(t){return`${new URL(t.url).pathname}`}s(ac,"instance");function uc(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},r=t.headers.get(je);return r&&(n.rayId=r),n}s(uc,"trace");var cc=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:ac(e),trace:uc(e,n),...r},additionalHeaders:o,statusText:Vt[t.status]}),"merge"),yr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?Oe.format(e,n,r):Oe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:wi[e],...n}}},O=class extends yr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=cc(this.getProblemFromStatus(e),n,r,o,i);return Oe.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:lc}=Object.prototype,{propertyIsEnumerable:dc}=Object.prototype;function br(t){return lc.call(t)}s(br,"toString");function se(t){return typeof t=="string"}s(se,"isString");function Ge(t){return se(t)&&t!==""}s(Ge,"isNonEmptyString");function Ri(t){return br(t)==="[object RegExp]"}s(Ri,"isRegexp");function Pi(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>dc.call(t,e))]}s(Pi,"getOwnEnumerableKeys");function De(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(De,"isObject");function wr(t){return typeof t=="number"&&!isNaN(t)}s(wr,"isNumber");function Rr(t){return t===!0||t===!1}s(Rr,"isBoolean");function Ei(t){return typeof t>"u"}s(Ei,"isUndefined");function Ii(t){return Ei(t)||t===null}s(Ii,"isUndefinedOrNull");function ht(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ht,"isErrorLike");var xi=new Map;function We(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=xi.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return xi.set(t,r),r}s(We,"statusCodesStringToNumberArray");function Ze(t,e,n){if(!e.startsWith("."))throw new y(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new L(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ze,"getValueFromRequestUser");function qe(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new y("Received an array that contains non-string values.");return t}if(se(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}s(qe,"parseValueToStringArray");function vi(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!De(n))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ge(n.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!wr(n.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Rr(n.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Pr(n,"allowedHeaders"),o=Pr(n,"allowedMethods"),i=Pr(n,"exposeHeaders"),a;try{a=qe(n.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(vi,"parseCorsPolicies");function Pr(t,e){let n;if(t[e]!==void 0)try{n=qe(t[e])}catch(r){throw new y(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Pr,"parseOptionalProperty");var zt=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Gt=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Er=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return O.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=t.lookup(l,c);if(!g)return O.notFound(a,u);let m=g.routeConfiguration,R=pc(l,d,p,m,n);return R.isValid?new Response(void 0,{status:200,statusText:"OK",headers:R.headers}):(R.error&&u.log.warn(R.error),O.notFound(a,u))},"optionsHandler"),o=new J({processors:[ne],handler:r,gateway:e}),i=new W({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),pc=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=zt(a.allowedOrigins,n);return u?{isValid:!0,headers:Gt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Ti=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new J({processors:[ne],handler:n,gateway:e}),o=new W({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Ir=new W({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Si=s((t,e)=>{let n=s(async(o,i)=>{let a=gt.value?.notFoundHandler;if(a){let u=te.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return O.notFound(o,i)},"notFoundHandler"),r=new J({processors:[ne],handler:n,gateway:e});t.addRoute(Ir,r.execute)},"registerNotMatchedHandler");var gc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Oi=s(t=>{gc.forEach(e=>t.delete(e))},"stripCorsHeaders"),Wt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Oi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=mc(o,n.routeData.corsPolicies),u=fc(t,a),c=new Headers(i.headers);return Oi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),mc=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),fc=s((t,e)=>{let n=zt(e.allowedOrigins,t.headers.get("origin"));return n?Gt(e,n):{}},"getCorsHeaders");var xr=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new J({processors:[Wt],handler:n,gateway:e}),o=new W({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Jt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!se(n))throw new L(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},pe=class extends Jt{static{s(this,"InboundPolicy")}},Ie=class extends Jt{static{s(this,"OutboundPolicy")}};var Sr=class extends pe{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},Or=class extends Ie{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},vr=new Map;function yt(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!vr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new y(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Sr(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);vr.set(a.name,c)}),n.map(i=>{let a=vr.get(i);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}s(yt,"getInboundPolicyInstances");var Tr=new Map;function hc(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!Tr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new y(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Ie)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Or(a,i.handler.options??{},i.name);else throw new y(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new y(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);Tr.set(i.name,u)}),n.map(o=>{let i=Tr.get(o);if(i===void 0)throw new L("Internal error. Policy not found in cache.");return i})}s(hc,"getOutboundPolicyInstances");var Cr=s(t=>async(e,n)=>{let r=te.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n);if(u instanceof j)i=u;else if(u instanceof Request)i=new j(u);else{if(u instanceof Response)return u;throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),yc=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new y(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Kt=s(async(t,e,n,r)=>{let o=yt(e.route,n.routeData.policies),i=hc(e.route,n.routeData.policies);return Ai({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Ci({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ai({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ci,"createInternalPolicyProcessor");async function Ai({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Cr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=yc(r),d;return x.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Ai,"executePolicyProcessor");function Li(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||bc,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=wc(l,o)}i=u+1}return n}s(Li,"parse");function bc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(bc,"decode");function wc(t,e){try{return e(t)}catch{return t}}s(wc,"tryDecode");function _i(t,e){try{let n=/v\d+(-\d+)?/g,o=Li(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(_i,"devPortalBaseURL");var Ni="/__zuplo/dev-portal",Rc="dev-portal-id",Pc="dev-portal-host",Ec="zp-account",Ic="zp-project",xc="dev-portal-build",vc=`
|
|
42
42
|
<!DOCTYPE html>
|
|
43
43
|
<html lang="en">
|
|
44
44
|
<head>
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
65
65
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
66
66
|
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Br(await ns(this.body||""))}return e}};async function vt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?jr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,jr.encode(e))}s(vt,"hmac");async function ns(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?jr.encode(t):t)}s(ns,"hash");function Br(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Br,"buf2hex");function rs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(rs,"encodeRfc3986");function Kc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in ts?[ts[i],a]:[i,a]}s(Kc,"guessServiceRegion");function Yc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(Yc,"b64ToUint6");function is(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Yc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(is,"base64Decode");function mn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(mn,"uint6ToB64");function ss(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(mn(o>>>18&63),mn(o>>>12&63),mn(o>>>6&63),mn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(ss,"base64Encode");function et(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(et,"numberToString");function Qc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=et(Math.floor(n/60)),i=et(n%60);return`${r}${o}${i}`}s(Qc,"getCLFOffset");function zr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=et(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=et(t.getHours()),a=et(t.getMinutes()),u=et(t.getSeconds()),c=Qc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(zr,"toCLFDate");var as=(0,us.debug)("zuplo:runtime"),Xc="X-Amzn-Trace-Id",el="x-amzn-errortype",cs=[],tl=s(async(t,e,n)=>{let r=n;for await(let o of cs)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),ue=class extends L{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Xc)??void 0,this.errorType=n.get(el)??void 0}},ls={addSendingAwsLambdaEventHook:t=>{cs.push(t)}};async function ds(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new y("awsAccessKeyId is not set in the handler options");if(!r)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!i)throw new y("functionName is not set in the handler options");let l=new Xe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(as(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,g]=await il(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,R;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?R=ol(t,e):R=await rl(t,e,{useAwsResourcePathStyle:u}),as("Calling onSendingAwsLambdaEvent hook");let w=await tl(t,e,R);w.body=p,w.isBase64Encoded=g;let I=await l.fetch(d,{body:JSON.stringify(w)});try{return nl(I)}catch(T){if(T instanceof ue){let f=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&T.traceId?{AMZN_TRACE_ID_HEADER:T.traceId}:void 0;return O.internalServerError(t,e,void 0,f)}throw T}}s(ds,"awsLambdaHandler");async function nl(t){let e;try{e=await t.json()}catch{throw new ue("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ue(e.message,t.headers):new ue(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ue(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ue(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ue(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ue("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new ue("Response was set to base64 encoded but body was not a string",t.headers);r=is(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(nl,"getResponse");async function rl(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:zr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:al(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(rl,"buildEventVersion1");function ol(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:zr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(ol,"buildEventVersion2");async function il(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&sl(e,o)){let i=await t.arrayBuffer();n=ss(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(il,"getBodyResult");function sl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(sl,"matchesContentType");function al(t,e=!1){if(!e)return t;let n=Fr(t),r=es(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(al,"getResourcePath");var ul=[502,503,504];async function tt(t,e){if(ul.includes(t.status)){let n=F.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(tt,"logBadGatewayResponses");var Gr;function _e(t){if(Gr===void 0){let n=x.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Gr=n}return t.log[Gr]}s(_e,"getHandlerUserLogFunction");async function ps(t,e){let n=x.instance.build.BUILD_ID,{buildAssetsUrl:r}=x.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=cl(i);if(!a.isValid)throw new y(a.error);let u;x.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return O.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return tt(l,e),l}s(ps,"openApiSpecHandler");var cl=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function gs(t,e){let n=e.route.handler.options;if(!n.location)throw new y("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(gs,"redirectHandler");function ll(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(ll,"join");async function ms(t,e){let n=_e(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=ll(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),g=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),tt(p,e),p}s(ms,"urlForwardHandler");var dl=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function fs(t,e){let n=_e(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?dl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),tt(d,e),d}s(fs,"urlRewriteHandler");async function hs(t,e){let n=x.instance,r=e.route.handler.options,o=_e(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await Ji(u),R=new URL(u);u=new URL(`${m.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let I in m.tunnelHeaders)p.set(I,m.tunnelHeaders[I])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let g=JSON.stringify({url:u});return new Response(g,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),g=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(g)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(hs,"webSocketHandler");var Wr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),ys=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function bs(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{let u=s(async c=>{let l=await ys(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(bs,"wireUpListeners");async function ws(t,e){let n=x.instance,r=e.route.handler.options,o=_e(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return O.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new y("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let T=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${T}'`;throw new Error(f)}let d=new WebSocketPair,[p,g]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let R=l.webSocket;R.accept(),g.accept();let w=r.policies&&r.policies.inbound?Wr(r.policies.inbound,"inbound"):[],I=r.policies&&r.policies.outbound?Wr(r.policies.outbound,"outbound"):[];return bs(g,R,t,e,w),bs(R,g,t,e,I),new Response(null,{status:101,webSocket:p})}s(ws,"webSocketPipelineHandler");var fn=class extends K{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new B("dyna-trace-log-transport",10,this.#i)};var hn=class extends K{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Yr(this.options)}},Kr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function pl(t,e){return btoa(`${t}:${e}`)}s(pl,"createBasicDigest");var Yr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=pl(e.username,e.password),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Kr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:xe(oe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new B("loki-log-transport",10,this.#s)};var yn=class extends K{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Qr(this.options)}},Qr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=x.instance.loggingEnvironmentType,this.#r=x.instance.loggingEnvironmentStage,this.#t=x.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:xe(oe(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
67
|
-
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new B("sumo-logic-log-transport",10,this.#s)};var gl="d3a5b78f823648f5b1df4fe269d41172",bn=class extends K{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){
|
|
67
|
+
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new B("sumo-logic-log-transport",10,this.#s)};var gl="d3a5b78f823648f5b1df4fe269d41172",bn=class extends K{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??gl}`)}catch{throw new y(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=x.instance.loggingEnvironmentType,this.#o=x.instance.loggingEnvironmentStage,this.#n=x.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Zi(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=_r(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let n=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new B("vmware-log-insights-log-transport",10,this.#a)};var wn=class extends K{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new B("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Xe({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=x.instance.loggingEnvironmentType,this.environment=x.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:xe(oe(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var to=new WeakMap,ml={tags:[]},Rn=class extends Ae{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new no(this.options)}static setContext(n,r){let o=to.get(n);o||(o=ml);let i=Object.assign({...o},r);to.set(n,i)}},no=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new B("data-dog-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(to.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new ro(await r.text())}},ro=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var oo=new WeakMap,fl={dimensions:[]},Pn=class extends Ae{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new io(this.options)}static setContext(n,r){let o=oo.get(n);o||(o=fl);let i=Object.assign({...o},r);oo.set(n,i)}},io=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new B("dynatrace-metrics-transport",10,this.dispatchFunction,F.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(oo.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
|
|
68
68
|
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new so(await r.text())}},so=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var En=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var In=class extends Ee{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new ao(e,this.#e,this.#t)}},Rs=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),hl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ao=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...hl};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new B("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Rs(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Rs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(g=>{n.log.error(g)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var uo=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Pe=class extends uo{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var yl="v1",bl=300;async function Ps(t,e,n,r=bl,o){return await Rl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(Ps,"constructEventAsync");function wl(t,e){return`${e.timestamp}.${t}`}s(wl,"makeHMACContent");async function Rl(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Pl(t,e,yl),l=/\s/.test(n),d=await vl(wl(a,u),n);return El(a,i,u,d,r,c,l,o)}s(Rl,"verifyHeaderAsync");function Pl(t,e,n){if(!t)throw new Pe(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),i=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Pe(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Il(a,n);if(!u||u.timestamp===-1)throw new Pe(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Pe(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Pl,"parseEventDetails");function El(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(g=>xl(g,r)).length,l=`
|
|
69
69
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
70
70
|
|
|
@@ -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}s(El,"validateComputedSignature");function Il(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Il,"parseHeader");function xl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(xl,"secureCompare");async function vl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=co[i[u]];return a.join("")}s(vl,"computeHMACSignatureAsync");var co=new Array(256);for(let t=0;t<co.length;t++)co[t]=t.toString(16).padStart(2,"0");function z(t,e,n="policy"){let r=`${n} '${e}'`;if(!De(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=s((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"),i=s((u,c)=>(o(u,c,!0),{optional:i,required:a}),"optional"),a=s((u,c)=>(o(u,c,!1),{optional:i,required:a}),"required");return{optional:i,required:a}}s(z,"optionValidator");var nt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){z(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 Ps(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a}return n.log.error("Error validating stripe webhook",i),O.badRequest(e,n,{title:"Webhook Error",detail:i})}return e}};function Es(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Es,"isStripeWebhookEvent");var xn=class extends Ee{static{s(this,"MeteringPlugin")}};var Tl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new L(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new L(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new L(i)}return o}},vn=Tl;var lo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Is({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,lo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,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}s(Is,"createConsumer");async function xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,lo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw i.log.error(g,p),new L(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(xs,"createConsumerInvite");async function vs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,lo);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(vs,"deleteConsumer");async function Ts({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=x.instance;if(!Ge(l))throw new q("No Zuplo JWT token set.");let p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let g="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}s(Ts,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new 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 Stripe metering plugin webhook.";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 Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}s(St,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),O.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}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),O.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return O.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await Ts({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await vs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),O.internalServerError(t,e,{detail:l.message})}return O.ok(t,e)}s(po,"onCustomerSubscriptionCreated");async function go(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),O.ok(t,e)}s(go,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),O.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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await vn.getUpcomingInvoice({customerId:i,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}}),O.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),O.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var fo=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(z(this.options.webhooks,"StripeMeteringPlugin","plugin").required("signingSecret","string").optional("tolerance","number"),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("StripeMeteringPlugin - 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("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!x.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Sl(g))throw new y(`StripeMeteringPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Es(m))return O.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 po(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await go(c,l,m,{meteringBucketId:d});default:return O.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Ci({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new J({processors:[ne,i],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 Sl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Sl,"isMetricsRegion");var Os=new WeakMap,Ss={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Os.set(e,n)}};async function Cs(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=We(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.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=Ss[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new B("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",T=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});T.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${T.status}: ${await T.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ss[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}s(Cs,"AmberfloMeteringInboundPolicy");async function On(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(On,"sha256");var As=new Map;async function X(t,e){let n,r=As.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,As.set(t,n)),n}s(X,"getPolicyCacheName");var Ls="key-metadata-cache-type";function Ol(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Ol,"getKeyValue");async function Cn(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 i=s(I=>o.allowUnauthenticatedRequests?t:O.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Ol(a,o);if(!u||u==="")return i("No key present");let c=await Cl(u),l=await X(r,o),d=new Y(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!==Ls&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),T=JSON.parse(I);e.log.error("Unexpected response from key service",T)}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(),w={isValid:!0,typeId:Ls,user:{sub:R.name,data:R.metadata}};return t.user=w.user,d.put(c,w,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Cl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Cl,"hashValue");var _s=Cn;var Ot=require("jose");var ho={},Al=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");ho[e.jwkUrl]||(ho[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,ho[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Ll=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(g=>O.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?Al:Ll,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(i.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 Ns=s(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 ks=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>O.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),m=d.substring(p+1),R=n.accounts.find(w=>w.username===g&&w.password===m);return R||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var _l=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Nl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Nl,"digestMessage");var kl=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Nl(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ms(t,e,n,r){let o=await X(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await kl(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);_l.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ms,"CachingInboundPolicy");var Us=s(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 Hs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ds=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Zs=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qs=s(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 $s=s(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,i=yt(n.policies,o?.routeData.policies);return Cr(i)(t,e)},"CompositeInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return O.unauthorized(t,e,{detail:"No authorization header"});let i=Ml(o);if(!i)return O.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Y(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),O.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):O.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Ml(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Ml,"getToken");var Bs=s(async(t,e,n,r)=>(z(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 js=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",Vs=s(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&i===rt,l=o.ignoreUnknown&&a===rt,d=o.ignoreUnknown&&u===rt,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ot(t,e,r,i,a,u);let R=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return R.length>0&&R.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?ot(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),O.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ot,"blockedResponse");function it(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[]`)}s(it,"toLowerStringArray");var zs=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Ws=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return yo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return yo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(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 Gs(a[u])}else return a.length>0?Gs(a[0]):yo(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 Gs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Gs,"generateResponse");var yo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return O.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ul="Incoming",Hl={logRequestBody:!0,logResponseBody:!0};function Js(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Js,"headersToObject");function Ks(){return new Date().toISOString()}s(Ks,"timestamp");var bo=new WeakMap,Dl={};function Xs(t,e){let n=bo.get(t);n||(n=Dl);let r=Object.assign({...n},e);bo.set(t,r)}s(Xs,"setMoesifContext");async function Ys(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Ys,"readBody");var Zl={},wo;function Qs(){if(!wo)throw new L("Invalid State - no _lastLogger");return wo}s(Qs,"getLastLogger");function ql(t){let e=Zl[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Qs().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||Qs().error({status:o.status,body:await o.text()})})),e}s(ql,"getDispatcher");async function ea(t,e,n,r){wo=e.log;let o=Ks(),i=Object.assign(Hl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ys(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=ql(i.applicationId),d=t.headers.get("true-client-ip"),p=bo.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Js(t.headers)},m=i.logResponseBody?await Ys(u,e):void 0,R={time:Ks(),status:u.status,headers:Js(u.headers),body:m},w={request:g,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ul};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(ea,"MoesifInboundPolicy");async function ta(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let 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}s(ta,"loadSubscription");async function na(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=x.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),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)}}s(na,"consumeSubcriptionQuotas");var $l=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new 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}}s(An,"validateMeters");function ra(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)$l.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"]}s(ra,"parseAllowedSubscriptionStatuses");function oa(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}}s(oa,"compareMeters");var Ln=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){An(n,"setMeters"),le.set(e,_t,n)}async handler(e,n){z(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-299");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),i=le.get(n,_t),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ra(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,T)=>{let f=le.get(T,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){T.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 A=le.get(T,_t),Z={...this.options.meters,...A};if(An(Z,this.policyName),o.includes(w.status)&&f&&Z){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${w.status}'`);let{metersInSubscription:h,metersNotInSubscription:b}=oa(f.meters,Z);if(b&&Object.keys(b).length>0){let S=Object.keys(b);T.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await na(T,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:O.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(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 ta(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:O.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),O.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),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"),O.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}'`),O.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),O.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return O.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var ia=s(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 Ro,aa=s(async(t,e,n,r)=>{if(!Ro)try{Ro=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:Ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ca=ke(Ue());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Po=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Eo=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Fl(t,e){if(Ii(t))throw new Po(e)}s(Fl,"throwIfUndefinedOrNull");function Ct(t,e){if(Fl(t,e),!se(t))throw new Eo(e,"string")}s(Ct,"throwIfNotString");var Nn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return 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 i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},kn=class{static{s(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:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new q("The in-memory redis client only supports /rate-limit calls")}};var Mn=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),Bl="strict",jl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Vl=s(async t=>({key:`ip-${jl(t)}`}),"getIP"),zl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Gl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function Wl(t,e){let n;if(Un)return Un;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new kn,Un=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Nn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}s(Wl,"getRedisClient");async function ua(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ua,"getCountAndUpdateExpiry");function Jl(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 s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new L(c)}return u},"outerFunction")}s(Jl,"wrapUserFunction");var Kl="Retry-After",Io=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new q(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Kl]=l.toString()),O.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Jl(n,r),user:zl,ip:Vl,all:Gl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,g=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,R=n.headerMode??"retry-after",w=Wl(r,i),T=`bucket/${x.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Bl)==="async"){let A=await X(r,n),Z=new ve(A,{logger:F.getLogger(e)}),h=ua(T,m,w,i,e.requestId),b=await Z.get(T);if(b!==void 0&&b<=Date.now()){Mn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${T}' (async mode)`);let S=Math.round((b-Date.now())/1e3);return u(R,S)}return e.addEventListener("responseSending",S=>{try{let k=S,C=k.mutableResponse;k.mutableResponse=(async()=>{let _=await h;if(_.count>g){let $=Date.now()+_.ttlSeconds*1e3,M=Z.put(T,$,_.ttlSeconds).catch(N=>{throw i.error(new q("Error caching rate limit result.",{cause:N})),N});return e.waitUntil(M),Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (async mode)`),u(R,_.ttlSeconds)}return C})()}catch(k){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,k)}}),t}let E=await ua(T,m,w,i,e.requestId);return E.count>g?(Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (strict mode)`),u(R,E.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Mn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var xo;function la(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(la,"headersToNameValuePairs");function Yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Yl,"queryToNameValueParis");function Ql(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Ql,"parseIntOrUndefined");var da={};async function pa(t,e,n,r){let o=new Date,i=Date.now();return xo||(xo={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.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:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:xo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:la(t.headers),queryString:Yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:la(a.headers),content:{size:Ql(t.headers.get("content-length"))}}}]}}},d=da[n.apiKey];if(!d){let p=n.apiKey;d=new B("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}s(pa,"ReadmeMetricsInboundPolicy");var ga=s(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 i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new j(t,{headers:i})},"RemoveHeadersInboundPolicy");var ma=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.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 i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var fa=s(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 i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new j(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ha=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ya=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ba=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ya():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ya():t},"RequestSizeLimitInboundPolicy");function wa(t,e,n){return`_${Ne(t+"_"+e+"_"+n)}`}s(wa,"getRawOperationDataIdentifierName");function Hn(t,e,n,r){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Hn,"getIdForParameterSchema");function Dn(t,e,n){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ne(n.toLowerCase())}`}s(Dn,"getIdForRequestBodySchema");function Ra(t,e){return`_${Ne(t)}__${Ne(e)}`}s(Ra,"getIdForRefSchema");function Ne(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(Ne,"sanitizedIdentifierName");var st=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),at=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Hn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=vo(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),vo=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Pa(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")}`,w=O.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 w}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=O.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"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Dn(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=O.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=vo(l),g=O.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}s(Pa,"handleBodyValidation");function Ea(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),i=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=O.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),he(n.validateHeaders))return u}}s(Ea,"handleHeadersValidation");function Ia(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=O.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}s(Ia,"handlePathParameterValidation");function xa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=O.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}s(xa,"handleQueryParameterValidation");var To=s(async(t,e,n)=>{let r=xa(e,t,n);if(r!==void 0||(r=Ia(e,t,n),r!==void 0)||(r=Ea(e,t,n),r!==void 0))return r;let o=await Pa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),va=To;var Ta=s(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 i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return O.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Sa=s(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Oa=s(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 i=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;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new j(t,{headers:i})},"SetHeadersInboundPolicy");var Ca=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new 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 Aa=s(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 i=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;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new j(i.toString(),t)},"SetQueryParamsInboundPolicy");var La=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Xl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),_a=s(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 Xl(n.sleepInMs),t},"SleepInboundPolicy");var Na=s(async(t,e,n,r)=>{z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await ee(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof j))throw new q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new 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?O.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var ka=s(async(t,e,n,r)=>{z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),i=new Y(o,e),a=await i.get(r);if(!a){let u=await ed(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ed(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new 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.")}s(ed,"getAccessToken");var Ma="https://accounts.google.com/o/oauth2/token",So,Ua=s(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string"),So||(So=await ae.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await X(r,n),a=new Y(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:So,audience:Ma,payload:o}),l=await en(Ma,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 td="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",nd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Oo,Ha=s(async(t,e,n,r)=>{if(z(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(nd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Oo||(Oo=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!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?.");i=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?`);i=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Y(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:Oo,audience:td,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await qi(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 Co,Da=s(async(t,e,n,r)=>{z(n,r).required("audience","string").required("serviceAccountJson","string"),Co||(Co=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:Co,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Za="https://www.googleapis.com/oauth2/v4/token",Ao,qa=s(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ao||(Ao=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 i=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Ao,audience:Za,payload:o}),l=await en(Za,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 $a=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return O.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new q("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return O.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Va=ke(ja());var Zn=class extends Ie{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),z(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?We(e.parseOnStatusCodes):void 0,this.parser=new Va.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 i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var qn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var _o=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!_o.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${_o.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 Bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var jn=class extends Bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new At("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new 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}s(El,"validateComputedSignature");function Il(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(Il,"parseHeader");function xl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(xl,"secureCompare");async function vl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=co[i[u]];return a.join("")}s(vl,"computeHMACSignatureAsync");var co=new Array(256);for(let t=0;t<co.length;t++)co[t]=t.toString(16).padStart(2,"0");function z(t,e,n="policy"){let r=`${n} '${e}'`;if(!De(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=s((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"),i=s((u,c)=>(o(u,c,!0),{optional:i,required:a}),"optional"),a=s((u,c)=>(o(u,c,!1),{optional:i,required:a}),"required");return{optional:i,required:a}}s(z,"optionValidator");var nt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){z(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 Ps(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a}return n.log.error("Error validating stripe webhook",i),O.badRequest(e,n,{title:"Webhook Error",detail:i})}return e}};function Es(t){return t!==null&&typeof t=="object"&&"id"in t&&se(t.id)&&"type"in t&&se(t.type)}s(Es,"isStripeWebhookEvent");var xn=class extends Ee{static{s(this,"MeteringPlugin")}};var Tl={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new L(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new L(i)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(i,o),new L(i)}return o}},vn=Tl;var lo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function Is({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=x.instance,c=new URL(`/v1/buckets/${t}/consumers`,lo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,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}s(Is,"createConsumer");async function xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=x.instance,u=new URL(`/v1/buckets/${t}/consumers`,lo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw i.log.error(g,p),new L(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(xs,"createConsumerInvite");async function vs({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=x.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,lo);o.searchParams.set("with-api-key","true");let i=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new L(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(vs,"deleteConsumer");async function Ts({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=x.instance;if(!Ge(l))throw new q("No Zuplo JWT token set.");let p=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let g="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(g,m),new L(g)}t.log.info("Successfully created/updated metering subscription.",c)}s(Ts,"createSubscription");async function Tt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new L(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(Tt,"updateSubscription");async function St({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=x.instance;if(!Ge(o))throw new q("No Zuplo JWT token set.");let a=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new 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 Stripe metering plugin webhook.";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 Stripe metering plugin webhook.";throw t.log.error(c),new L(c)}return u.data[0]}s(St,"getSubscription");function Tn(t){return t.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");async function po(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),O.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}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await vn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),O.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return O.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=Tn(n.data.object.status);await Ts({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await vs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),O.internalServerError(t,e,{detail:l.message})}return O.ok(t,e)}s(po,"onCustomerSubscriptionCreated");async function go(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await Tt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),O.ok(t,e)}s(go,"onCustomerSubscriptionDeleted");async function mo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),O.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),O.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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Tn(n.data.object.status);return await Tt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),O.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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await vn.getUpcomingInvoice({customerId:i,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}}),O.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),O.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(mo,"onCustomerSubscriptionUpdated");var fo=class extends xn{constructor(n){super();this.options=n}static{s(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(z(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number"),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(!x.instance.build.ACCOUNT_NAME)throw new q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.meteringBucketRegion??"us-central1";if(!Sl(g))throw new y(`StripeMonetizationPlugin - The value '${g}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Es(m))return O.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 po(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mo(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await go(c,l,m,{meteringBucketId:d});default:return O.badRequest(c,l,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=Ci({inboundPolicies:[new nt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new J({processors:[ne,i],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 Sl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Sl,"isMetricsRegion");var Os=new WeakMap,Ss={},Sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Os.set(e,n)}};async function Cs(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=We(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.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=Ss[n.apiKey];if(!g){let m=n.apiKey,R=t.headers.get("zm-test-id")??"";g=new B("amberflo-ingest-meter",10,async w=>{try{let I=n.url??"https://app.amberflo.io/ingest",T=await fetch(I,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":R}});T.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${T.status}: ${await T.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ss[m]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),t}s(Cs,"AmberfloMeteringInboundPolicy");async function On(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(On,"sha256");var As=new Map;async function X(t,e){let n,r=As.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await On(JSON.stringify({policyName:t,options:e}))}`,As.set(t,n)),n}s(X,"getPolicyCacheName");var Ls="key-metadata-cache-type";function Ol(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Ol,"getKeyValue");async function Cn(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 i=s(I=>o.allowUnauthenticatedRequests?t:O.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Ol(a,o);if(!u||u==="")return i("No key present");let c=await Cl(u),l=await X(r,o),d=new Y(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!==Ls&&F.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},m=await ie({retryDelayMs:5,retries:2,logger:F.getLogger(e)},`${x.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":x.instance.deploymentName??"unknown","User-Agent":x.instance.systemUserAgent},body:JSON.stringify(g)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),T=JSON.parse(I);e.log.error("Unexpected response from key service",T)}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(),w={isValid:!0,typeId:Ls,user:{sub:R.name,data:R.metadata}};return t.user=w.user,d.put(c,w,o.cacheTtlSeconds),t}s(Cn,"ApiKeyInboundPolicy");async function Cl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Cl,"hashValue");var _s=Cn;var Ot=require("jose");var ho={},Al=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");ho[e.jwkUrl]||(ho[e.jwkUrl]=(0,Ot.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,Ot.jwtVerify)(t,ho[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Ll=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,Ot.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ee=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(g=>O.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?Al:Ll,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(i.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 Ns=s(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 ks=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>O.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),m=d.substring(p+1),R=n.accounts.find(w=>w.username===g&&w.password===m);return R||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var _l=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Nl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Nl,"digestMessage");var kl=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Nl(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Ms(t,e,n,r){let o=await X(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await kl(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let g=n?.expirationSecondsTtl??60,m=new Response(p.body,p);_l.forEach(R=>m.headers.delete(R)),m.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ms,"CachingInboundPolicy");var Us=s(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 Hs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ds=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Zs=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",ee(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var qs=s(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 $s=s(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,i=yt(n.policies,o?.routeData.policies);return Cr(i)(t,e)},"CompositeInboundPolicy");var Fs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return O.unauthorized(t,e,{detail:"No authorization header"});let i=Ml(o);if(!i)return O.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await X(r,n),u=new Y(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),O.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):O.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Ml(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Ml,"getToken");var Bs=s(async(t,e,n,r)=>(z(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 js=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var rt="__unknown__",Vs=s(async(t,e,n,r)=>{let o={allow:{countries:it(n.allow?.countries,"allow.countries",r),regionCodes:it(n.allow?.regionCodes,"allow.regionCode",r),asns:it(n.allow?.asns,"allow.asOrganization",r)},block:{countries:it(n.block?.countries,"block.countries",r),regionCodes:it(n.block?.regionCodes,"block.regionCode",r),asns:it(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??rt,u=e.incomingRequestProperties.asn?.toString()??rt,c=o.ignoreUnknown&&i===rt,l=o.ignoreUnknown&&a===rt,d=o.ignoreUnknown&&u===rt,p=o.allow.countries,g=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ot(t,e,r,i,a,u);let R=o.block.countries,w=o.block.regionCodes,I=o.block.asns;return R.length>0&&R.includes(i)&&!c||w.length>0&&w.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?ot(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ot(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),O.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ot,"blockedResponse");function it(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[]`)}s(it,"toLowerStringArray");var zs=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Ws=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return yo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return yo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(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 Gs(a[u])}else return a.length>0?Gs(a[0]):yo(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 Gs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Gs,"generateResponse");var yo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return O.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Ul="Incoming",Hl={logRequestBody:!0,logResponseBody:!0};function Js(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Js,"headersToObject");function Ks(){return new Date().toISOString()}s(Ks,"timestamp");var bo=new WeakMap,Dl={};function Xs(t,e){let n=bo.get(t);n||(n=Dl);let r=Object.assign({...n},e);bo.set(t,r)}s(Xs,"setMoesifContext");async function Ys(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Ys,"readBody");var Zl={},wo;function Qs(){if(!wo)throw new L("Invalid State - no _lastLogger");return wo}s(Qs,"getLastLogger");function ql(t){let e=Zl[t];return e||(e=new B("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Qs().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||Qs().error({status:o.status,body:await o.text()})})),e}s(ql,"getDispatcher");async function ea(t,e,n,r){wo=e.log;let o=Ks(),i=Object.assign(Hl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ys(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=ql(i.applicationId),d=t.headers.get("true-client-ip"),p=bo.get(e)??{},g={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Js(t.headers)},m=i.logResponseBody?await Ys(u,e):void 0,R={time:Ks(),status:u.status,headers:Js(u.headers),body:m},w={request:g,response:R,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ul};l.enqueue(w),e.waitUntil(l.waitUntilFlushed())}),t}s(ea,"MoesifInboundPolicy");async function ta(t,e,n,r){let o=F.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=x.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let 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}s(ta,"loadSubscription");async function na(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=x.instance,u=F.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),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)}}s(na,"consumeSubcriptionQuotas");var $l=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new 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}}s(An,"validateMeters");function ra(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)$l.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"]}s(ra,"parseAllowedSubscriptionStatuses");function oa(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}}s(oa,"compareMeters");var Ln=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return le.get(e,lt)}static setMeters(e,n){An(n,"setMeters"),le.set(e,_t,n)}async handler(e,n){z(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-299");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),i=le.get(n,_t),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ra(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(w,I,T)=>{let f=le.get(T,lt);if((this.options.allowRequestsWithoutSubscription??!1)&&!f){T.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 A=le.get(T,_t),Z={...this.options.meters,...A};if(An(Z,this.policyName),o.includes(w.status)&&f&&Z){T.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${f.id}' with meters '${JSON.stringify(Z)} on response status '${w.status}'`);let{metersInSubscription:h,metersNotInSubscription:b}=oa(f.meters,Z);if(b&&Object.keys(b).length>0){let S=Object.keys(b);T.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await na(T,f.id,this.policyName,this.options.bucketId,h)}});let l=e.user;if(!l)return u?e:O.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(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 ta(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:O.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),O.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),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"),O.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}'`),O.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let R=Object.keys(a).filter(w=>!Object.keys(g.meters).includes(w));if(R.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${R.join(", ")}`),O.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${R.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(a))if(g.meters[w].consumed<=0&&!r)return O.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return e}};var ia=s(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 Ro,aa=s(async(t,e,n,r)=>{if(!Ro)try{Ro=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:Ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ca=ke(Ue());var _n=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Po=class extends _n{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Eo=class extends _n{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Fl(t,e){if(Ii(t))throw new Po(e)}s(Fl,"throwIfUndefinedOrNull");function Ct(t,e){if(Fl(t,e),!se(t))throw new Eo(e,"string")}s(Ct,"throwIfNotString");var Nn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return 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 i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new q("Redis client failed with 401: Unauthorized"):new q(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},kn=class{static{s(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:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new q("The in-memory redis client only supports /rate-limit calls")}};var Mn=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),Bl="strict",jl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Vl=s(async t=>({key:`ip-${jl(t)}`}),"getIP"),zl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Gl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Un;function Wl(t,e){let n;if(Un)return Un;if(x.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new kn,Un=n,n;let{authApiJWT:r,redisURL:o}=x.instance;if(!se(o))throw new q(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!se(r))throw new q(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Nn.initialize(o,r,x.instance.deploymentName??"unknown",x.instance.systemUserAgent)),!n||!n.isEnabled())throw new q(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Un=n,n}s(Wl,"getRedisClient");async function ua(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(ua,"getCountAndUpdateExpiry");function Jl(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 s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new L(c)}return u},"outerFunction")}s(Jl,"wrapUserFunction");var Kl="Retry-After",Io=s(async(t,e,n,r)=>{let o=Date.now(),i=F.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new q(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Kl]=l.toString()),O.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Jl(n,r),user:zl,ip:Vl,all:Gl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,g=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,R=n.headerMode??"retry-after",w=Wl(r,i),T=`bucket/${x.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Bl)==="async"){let A=await X(r,n),Z=new ve(A,{logger:F.getLogger(e)}),h=ua(T,m,w,i,e.requestId),b=await Z.get(T);if(b!==void 0&&b<=Date.now()){Mn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${T}' (async mode)`);let S=Math.round((b-Date.now())/1e3);return u(R,S)}return e.addEventListener("responseSending",S=>{try{let k=S,C=k.mutableResponse;k.mutableResponse=(async()=>{let _=await h;if(_.count>g){let $=Date.now()+_.ttlSeconds*1e3,M=Z.put(T,$,_.ttlSeconds).catch(N=>{throw i.error(new q("Error caching rate limit result.",{cause:N})),N});return e.waitUntil(M),Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (async mode)`),u(R,_.ttlSeconds)}return C})()}catch(k){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,k)}}),t}let E=await ua(T,m,w,i,e.requestId);return E.count>g?(Mn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${T}' (strict mode)`),u(R,E.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Mn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var xo;function la(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(la,"headersToNameValuePairs");function Yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Yl,"queryToNameValueParis");function Ql(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Ql,"parseIntOrUndefined");var da={};async function pa(t,e,n,r){let o=new Date,i=Date.now();return xo||(xo={name:"zuplo",version:x.instance.build.ZUPLO_VERSION,comment:`zuplo/${x.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:x.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:xo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:la(t.headers),queryString:Yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:la(a.headers),content:{size:Ql(t.headers.get("content-length"))}}}]}}},d=da[n.apiKey];if(!d){let p=n.apiKey;d=new B("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}s(pa,"ReadmeMetricsInboundPolicy");var ga=s(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 i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new j(t,{headers:i})},"RemoveHeadersInboundPolicy");var ma=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.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 i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var fa=s(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 i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new j(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ha=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ya=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ba=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ya():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ya():t},"RequestSizeLimitInboundPolicy");function wa(t,e,n){return`_${Ne(t+"_"+e+"_"+n)}`}s(wa,"getRawOperationDataIdentifierName");function Hn(t,e,n,r){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Hn,"getIdForParameterSchema");function Dn(t,e,n){return`_${Ne(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ne(n.toLowerCase())}`}s(Dn,"getIdForRequestBodySchema");function Ra(t,e){return`_${Ne(t)}__${Ne(e)}`}s(Ra,"getIdForRefSchema");function Ne(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(Ne,"sanitizedIdentifierName");var st=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),at=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Hn(n,r,o,c.name),p=Q.instance.schemaValidator[d],g=p(e[c.name]),m=vo(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),me=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),fe=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),he=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),vo=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Pa(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")}`,w=O.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 w}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=O.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"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Dn(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=O.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=vo(l),g=O.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}s(Pa,"handleBodyValidation");function Ea(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=st(t),i=at(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=O.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(fe(n.validateHeaders)&&me(t,n.logLevel??"info",a,i.invalidValues,i.errors),he(n.validateHeaders))return u}}s(Ea,"handleHeadersValidation");function Ia(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=st(t),o=at(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=O.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validatePathParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validatePathParameters))return a}}s(Ia,"handlePathParameterValidation");function xa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=st(t),o=at(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=O.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(fe(n.validateQueryParameters)&&me(t,n.logLevel??"info",i,o.invalidValues,o.errors),he(n.validateQueryParameters))return a}}s(xa,"handleQueryParameterValidation");var To=s(async(t,e,n)=>{let r=xa(e,t,n);if(r!==void 0||(r=Ia(e,t,n),r!==void 0)||(r=Ea(e,t,n),r!==void 0))return r;let o=await Pa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),va=To;var Ta=s(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 i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return O.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Sa=s(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Oa=s(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 i=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;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new j(t,{headers:i})},"SetHeadersInboundPolicy");var Ca=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new 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 Aa=s(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 i=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;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new j(i.toString(),t)},"SetQueryParamsInboundPolicy");var La=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Xl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),_a=s(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 Xl(n.sleepInMs),t},"SleepInboundPolicy");var Na=s(async(t,e,n,r)=>{z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await ee(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof j))throw new q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new 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?O.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var ka=s(async(t,e,n,r)=>{z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await X(r,n),i=new Y(o,e),a=await i.get(r);if(!a){let u=await ed(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function ed(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ie({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new 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.")}s(ed,"getAccessToken");var Ma="https://accounts.google.com/o/oauth2/token",So,Ua=s(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string"),So||(So=await ae.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await X(r,n),a=new Y(i,e),u=await a.get(r);if(!u){let c=await we({serviceAccount:So,audience:Ma,payload:o}),l=await en(Ma,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 td="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",nd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Oo,Ha=s(async(t,e,n,r)=>{if(z(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(nd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Oo||(Oo=await ae.init(n.serviceAccountJson));let i=n.userId;if(!i&&!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?.");i=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?`);i=Ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new L(`Unable to determine user from for the policy ${r}`);let a=await X(r,n),u=new Y(a,e),c={uid:i,claims:o},l=await On(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await we({serviceAccount:Oo,audience:td,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await qi(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 Co,Da=s(async(t,e,n,r)=>{z(n,r).required("audience","string").required("serviceAccountJson","string"),Co||(Co=await ae.init(n.serviceAccountJson));let o=await we({serviceAccount:Co,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Za="https://www.googleapis.com/oauth2/v4/token",Ao,qa=s(async(t,e,n,r)=>{z(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ao||(Ao=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 i=await X(r,n),a;n.useMemoryCacheOnly?a=new Be(i):a=new Y(i,e);let u=await a.get(r);if(!u){let c=await we({serviceAccount:Ao,audience:Za,payload:o}),l=await en(Za,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 $a=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return O.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new q("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return O.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Va=ke(ja());var Zn=class extends Ie{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),z(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?We(e.parseOnStatusCodes):void 0,this.parser=new Va.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 i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var qn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new q(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var _o=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{s(this,"BaseCryptoBeta")}};var Fn=class extends $n{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!_o.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${_o.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 Bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var jn=class extends Bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new At("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new 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 */
|