@zuplo/runtime 5.2178.0 → 5.2180.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/out/cjs/index.js +21 -21
- package/out/esm/index.js +18 -18
- package/out/types/index.d.ts +4 -0
- package/package.json +1 -1
package/out/cjs/index.js
CHANGED
|
@@ -22,17 +22,17 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var
|
|
26
|
-
`).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(
|
|
25
|
+
"use strict";var ac=Object.create;var Mt=Object.defineProperty;var uc=Object.getOwnPropertyDescriptor;var cc=Object.getOwnPropertyNames;var lc=Object.getPrototypeOf,dc=Object.prototype.hasOwnProperty;var i=(n,e)=>Mt(n,"name",{value:e,configurable:!0});var Dt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),pc=(n,e)=>{for(var t in e)Mt(n,t,{get:e[t],enumerable:!0})},Ai=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cc(e))!dc.call(n,o)&&o!==t&&Mt(n,o,{get:()=>e[o],enumerable:!(r=uc(e,o))||r.enumerable});return n};var et=(n,e,t)=>(t=n!=null?ac(lc(n)):{},Ai(e||!n||!n.__esModule?Mt(t,"default",{value:n,enumerable:!0}):t,n)),mc=n=>Ai(Mt({},"__esModule",{value:!0}),n);var Zi=Dt(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var _i=!0,Nr=!_i;function gc(n){_i||(Nr=n)}i(gc,"setColorEnabled");v.setColorEnabled=gc;function fc(){return Nr}i(fc,"getColorEnabled");v.getColorEnabled=fc;function J(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(J,"code");function K(n,e){return Nr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(K,"run");function hc(n){return K(n,J([0],0))}i(hc,"reset");v.reset=hc;function yc(n){return K(n,J([1],22))}i(yc,"bold");v.bold=yc;function bc(n){return K(n,J([2],22))}i(bc,"dim");v.dim=bc;function wc(n){return K(n,J([3],23))}i(wc,"italic");v.italic=wc;function Rc(n){return K(n,J([4],24))}i(Rc,"underline");v.underline=Rc;function Pc(n){return K(n,J([7],27))}i(Pc,"inverse");v.inverse=Pc;function Ec(n){return K(n,J([8],28))}i(Ec,"hidden");v.hidden=Ec;function Ic(n){return K(n,J([9],29))}i(Ic,"strikethrough");v.strikethrough=Ic;function xc(n){return K(n,J([30],39))}i(xc,"black");v.black=xc;function Li(n){return K(n,J([31],39))}i(Li,"red");v.red=Li;function ki(n){return K(n,J([32],39))}i(ki,"green");v.green=ki;function Ni(n){return K(n,J([33],39))}i(Ni,"yellow");v.yellow=Ni;function Mi(n){return K(n,J([34],39))}i(Mi,"blue");v.blue=Mi;function Di(n){return K(n,J([35],39))}i(Di,"magenta");v.magenta=Di;function Ui(n){return K(n,J([36],39))}i(Ui,"cyan");v.cyan=Ui;function Tc(n){return K(n,J([37],39))}i(Tc,"white");v.white=Tc;function vc(n){return Hi(n)}i(vc,"gray");v.gray=vc;function Hi(n){return K(n,J([90],39))}i(Hi,"brightBlack");v.brightBlack=Hi;function Sc(n){return K(n,J([91],39))}i(Sc,"brightRed");v.brightRed=Sc;function Oc(n){return K(n,J([92],39))}i(Oc,"brightGreen");v.brightGreen=Oc;function Cc(n){return K(n,J([93],39))}i(Cc,"brightYellow");v.brightYellow=Cc;function Ac(n){return K(n,J([94],39))}i(Ac,"brightBlue");v.brightBlue=Ac;function _c(n){return K(n,J([95],39))}i(_c,"brightMagenta");v.brightMagenta=_c;function Lc(n){return K(n,J([96],39))}i(Lc,"brightCyan");v.brightCyan=Lc;function kc(n){return K(n,J([97],39))}i(kc,"brightWhite");v.brightWhite=kc;function Nc(n){return K(n,J([40],49))}i(Nc,"bgBlack");v.bgBlack=Nc;function Mc(n){return K(n,J([41],49))}i(Mc,"bgRed");v.bgRed=Mc;function Dc(n){return K(n,J([42],49))}i(Dc,"bgGreen");v.bgGreen=Dc;function Uc(n){return K(n,J([43],49))}i(Uc,"bgYellow");v.bgYellow=Uc;function Hc(n){return K(n,J([44],49))}i(Hc,"bgBlue");v.bgBlue=Hc;function Zc(n){return K(n,J([45],49))}i(Zc,"bgMagenta");v.bgMagenta=Zc;function qc(n){return K(n,J([46],49))}i(qc,"bgCyan");v.bgCyan=qc;function Fc(n){return K(n,J([47],49))}i(Fc,"bgWhite");v.bgWhite=Fc;function $c(n){return K(n,J([100],49))}i($c,"bgBrightBlack");v.bgBrightBlack=$c;function jc(n){return K(n,J([101],49))}i(jc,"bgBrightRed");v.bgBrightRed=jc;function Bc(n){return K(n,J([102],49))}i(Bc,"bgBrightGreen");v.bgBrightGreen=Bc;function zc(n){return K(n,J([103],49))}i(zc,"bgBrightYellow");v.bgBrightYellow=zc;function Vc(n){return K(n,J([104],49))}i(Vc,"bgBrightBlue");v.bgBrightBlue=Vc;function Gc(n){return K(n,J([105],49))}i(Gc,"bgBrightMagenta");v.bgBrightMagenta=Gc;function Wc(n){return K(n,J([106],49))}i(Wc,"bgBrightCyan");v.bgBrightCyan=Wc;function Jc(n){return K(n,J([107],49))}i(Jc,"bgBrightWhite");v.bgBrightWhite=Jc;function je(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(je,"clampAndTruncate");function Kc(n,e){return K(n,J([38,5,je(e)],39))}i(Kc,"rgb8");v.rgb8=Kc;function Yc(n,e){return K(n,J([48,5,je(e)],49))}i(Yc,"bgRgb8");v.bgRgb8=Yc;function Xc(n,e){return typeof e=="number"?K(n,J([38,2,e>>16&255,e>>8&255,e&255],39)):K(n,J([38,2,je(e.r),je(e.g),je(e.b)],39))}i(Xc,"rgb24");v.rgb24=Xc;function Qc(n,e){return typeof e=="number"?K(n,J([48,2,e>>16&255,e>>8&255,e&255],49)):K(n,J([48,2,je(e.r),je(e.g),je(e.b)],49))}i(Qc,"bgRgb24");v.bgRgb24=Qc;var el=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function tl(n){return n.replace(el,"")}i(tl,"stripColor");v.stripColor=tl;v.colorFunctions=[Li,ki,Ni,Mi,Di,Ui];function nl(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(nl,"hashCode");function rl(n){let e=Math.abs(nl(n));return v.colorFunctions[e%v.colorFunctions.length]}i(rl,"generateColor");v.generateColor=rl});var qi=Dt(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.format=void 0;function ol(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
|
|
26
|
+
`).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(ol,"format");tn.format=ol});var Vi=Dt(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.inspect=void 0;function tt(n,e,t,r){let o={seen:[],stylize:il,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=al),nn(o,n,o.depth)}i(tt,"inspect");rn.inspect=tt;tt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};tt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function il(n,e){return n}i(il,"stylizeNoColor");function sl(n){return typeof n=="boolean"}i(sl,"isBoolean");function $i(n){return n===void 0}i($i,"isUndefined");function al(n,e){let t=tt.styles[e];return t?"\x1B["+tt.colors[t][0]+"m"+n+"\x1B["+tt.colors[t][1]+"m":n}i(al,"stylizeWithColor");function Mr(n){return typeof n=="function"}i(Mr,"isFunction");function ji(n){return typeof n=="string"}i(ji,"isString");function ul(n){return typeof n=="number"}i(ul,"isNumber");function Bi(n){return n===null}i(Bi,"isNull");function zi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(zi,"hasOwn");function Dr(n){return qr(n)&&Fr(n)==="[object RegExp]"}i(Dr,"isRegExp");function qr(n){return typeof n=="object"&&n!==null}i(qr,"isObject");function Ur(n){return qr(n)&&(Fr(n)==="[object Error]"||n instanceof Error)}i(Ur,"isError");function Fi(n){return qr(n)&&Fr(n)==="[object Date]"}i(Fi,"isDate");function Fr(n){return Object.prototype.toString.call(n)}i(Fr,"objectToString");function cl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(cl,"arrayToHash");function ll(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)zi(e,String(a))?s.push(Zr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Zr(n,e,t,r,a,!0))}),s}i(ll,"formatArray");function Hr(n){return"["+Error.prototype.toString.call(n)+"]"}i(Hr,"formatError");function nn(n,e,t){if(n.customInspect&&e&&Mr(e.inspect)&&e.inspect!==tt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return ji(d)||(d=nn(n,d,t)),d}let r=dl(n,e);if(r)return r;let o=Object.keys(e),s=cl(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Ur(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Hr(e);if(o.length===0){if(Mr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Dr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Fi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Ur(e))return Hr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Mr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Dr(e)&&(a=" "+RegExp.prototype.toString.call(e)),Fi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Ur(e)&&(a=" "+Hr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Dr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=ll(n,e,t,s,o):l=o.map(function(d){return Zr(n,e,t,s,d,u)}),n.seen.pop(),pl(l,a,c)}i(nn,"formatValue");function Zr(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),zi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Bi(t)?u=nn(n,c.value,null):u=nn(n,c.value,t-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(s?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
29
29
|
`).substr(2):u=`
|
|
30
30
|
`+u.split(`
|
|
31
31
|
`).map(function(l){return" "+l}).join(`
|
|
32
|
-
`))):u=n.stylize("[Circular]","special"))
|
|
32
|
+
`))):u=n.stylize("[Circular]","special")),$i(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Zr,"formatProperty");function dl(n,e){if($i(e))return n.stylize("undefined","undefined");if(ji(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ul(e))return n.stylize(""+e,"number");if(sl(e))return n.stylize(""+e,"boolean");if(Bi(e))return n.stylize("null","null")}i(dl,"formatPrimitive");function pl(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+n.join(`,
|
|
35
|
-
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(al,"reduceToSingleString")});var zi=Mt(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.format=void 0;var ul=Hi(),cl=Bi(),ll=i((n,...e)=>(0,ul.format)(cl.inspect,n,e),"format");rn.format=ll});var Be=Mt(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.debug=je.withoutEnv=je.Debugger=void 0;var dl=Ui(),pl=zi(),on=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,dl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,pl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};je.Debugger=on;var sn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Vi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Vi,"extract");var Dt;function ml(n){n||(n=[]),typeof n=="string"&&(n=Vi(n)),Dt=new sn(n)}i(ml,"withoutEnv");je.withoutEnv=ml;function gl(n){let e=globalThis.DEBUG;Dt||(Dt=new sn(Vi(e)));let t=new on(Dt,n);return Dt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(gl,"debug");je.debug=gl});var Ep={};ac(Ep,{AWSLoggingPlugin:()=>zn,AmberfloMeteringInboundPolicy:()=>Na,AmberfloMeteringPolicy:()=>Xn,ApiAuthKeyInboundPolicy:()=>Ua,ApiKeyInboundPolicy:()=>er,AuditLogDataStaxProvider:()=>Wn,AuditLogPlugin:()=>Jn,Auth0JwtInboundPolicy:()=>qa,AwsLambdaHandlerExtensions:()=>ga,AxiomaticsAuthZInboundPolicy:()=>rr,BackgroundDispatcher:()=>xr,BackgroundLoader:()=>Tr,BasicAuthInboundPolicy:()=>$a,BasicRateLimitInboundPolicy:()=>yi,BatchDispatch:()=>Y,BrownoutInboundPolicy:()=>sr,CachingInboundPolicy:()=>ja,ChangeMethodInboundPolicy:()=>Ba,ClearHeadersInboundPolicy:()=>za,ClearHeadersOutboundPolicy:()=>Va,ClerkJwtInboundPolicy:()=>Ga,CognitoJwtInboundPolicy:()=>Wa,CompositeInboundPolicy:()=>Ja,ConfigurationError:()=>m,ContentTypes:()=>mn,ContextData:()=>Oe,CryptoBeta:()=>Sr,CurityPhantomTokenInboundPolicy:()=>Ka,DataDogLoggingPlugin:()=>An,DataDogMetricsPlugin:()=>Vn,DynaTraceLoggingPlugin:()=>$n,DynatraceMetricsPlugin:()=>Gn,FirebaseJwtInboundPolicy:()=>Ya,FormDataToJsonInboundPolicy:()=>Xa,GeoFilterInboundPolicy:()=>Qa,GoogleCloudLoggingPlugin:()=>Sn,Handler:()=>Zn,HttpProblems:()=>x,HttpStatusCode:()=>$t,InboundPolicy:()=>be,JWTScopeValidationInboundPolicy:()=>eu,KeyValueStore:()=>Cr,LokiLoggingPlugin:()=>Fn,LookupResult:()=>Rt,MemoryZoneReadThroughCache:()=>le,MockApiInboundPolicy:()=>nu,MoesifInboundPolicy:()=>uu,MonetizationInboundPolicy:()=>ur,OktaJwtInboundPolicy:()=>mu,OpenIdJwtInboundPolicy:()=>ge,OutboundPolicy:()=>qe,ProblemResponseFormatter:()=>Ve,PropelAuthJwtInboundPolicy:()=>fu,RateLimitInboundPolicy:()=>yi,ReadmeMetricsInboundPolicy:()=>Iu,RemoveHeadersInboundPolicy:()=>xu,RemoveHeadersOutboundPolicy:()=>Tu,RemoveQueryParamsInboundPolicy:()=>vu,ReplaceStringOutboundPolicy:()=>Su,RequestSizeLimitInboundPolicy:()=>Cu,RequestValidationInboundPolicy:()=>Ri,RequireOriginInboundPolicy:()=>Uu,ResponseSendingEvent:()=>gt,ResponseSentEvent:()=>ft,Router:()=>Pt,RuntimeError:()=>_,SYSTEM_LOGGER:()=>Ht,SchemaBasedRequestValidation:()=>Du,SemanticAttributes:()=>Ae,ServiceProviderImpl:()=>Ir,SetBodyInboundPolicy:()=>Hu,SetHeadersInboundPolicy:()=>Zu,SetHeadersOutboundPolicy:()=>qu,SetQueryParamsInboundPolicy:()=>$u,SetStatusOutboundPolicy:()=>Fu,SleepInboundPolicy:()=>ju,StripeMonetizationPlugin:()=>ii,StripeWebhookVerificationInboundPolicy:()=>Tt,SumoLogicLoggingPlugin:()=>jn,SupabaseJwtInboundPolicy:()=>Bu,SystemRouteName:()=>Ne,TelemetryPlugin:()=>pt,UpstreamAzureAdServiceAuthInboundPolicy:()=>zu,UpstreamFirebaseAdminAuthInboundPolicy:()=>Gu,UpstreamFirebaseUserAuthInboundPolicy:()=>Wu,UpstreamGcpJwtInboundPolicy:()=>Ju,UpstreamGcpServiceAuthInboundPolicy:()=>Yu,VMWareLogInsightLoggingPlugin:()=>Bn,ValidateJsonSchemaInbound:()=>Xu,XmlToJsonOutboundPolicy:()=>Er,ZoneCache:()=>dt,ZuploRequest:()=>ne,awsLambdaHandler:()=>fa,environment:()=>we,getIdForParameterSchema:()=>Rr,getIdForRefSchema:()=>_u,getIdForRequestBodySchema:()=>Pr,getRawOperationDataIdentifierName:()=>Au,httpStatuses:()=>hn,openApiSpecHandler:()=>ha,redirectHandler:()=>ya,sanitizedIdentifierName:()=>Xe,serialize:()=>gn,setMoesifContext:()=>au,urlForwardHandler:()=>ba,urlRewriteHandler:()=>wa,webSocketHandler:()=>Ra,webSocketPipelineHandler:()=>Ia});module.exports=uc(Ep);var Ki=Qe(Be());var X=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},_=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends _{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},an=class extends _{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var qr="2024-03-14",Gi=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Wi(){return new g({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:qr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Gi[qr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(Wi,"getMockEnvironment");var g=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Wi()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var tt=(0,Ki.debug)("zuplo:runtime:external-service");function fl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=g.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(fl,"getServiceAuth");async function Yi(n,e){let t=fl();if(t)if(tt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(g.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{tt("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await hl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw tt("Cannot use sha256 service routing, missing build variables"),new _("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);tt(`Calling external service: ${c.toString()}`);let l=await q.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new _("Could not connect to secure tunnel.");return l}else throw tt("Cannot call external service with Request object"),new _("Currently, we only support fetch(<some_string>, ...).");else throw tt("There is no external service auth configured for this zup."),new _("There are no external services configured for this zup.")}i(Yi,"externalServiceHandler");async function hl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=yl(r);tt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ji(`${s}-${o}`),l=await Ji(`${s}-${a}-${u}`);return`${c}.${l}`}i(hl,"hashServiceName");async function Ji(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ji,"hashSegment");function yl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(yl,"sanitizeEnvironmentType");var Qi=new Map;Qi.set("service:",Yi);var Xi=globalThis.fetch;function $r(n,e){let t=bl(e);if(typeof n=="string"){let r=new URL(n),o=Qi.get(r.protocol);return o?o(n,t):Xi(n,t)}else return Xi(n,t)}i($r,"internalFetch");globalThis.fetch=$r;var bl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var wl={fetch:$r},q=wl;Function.prototype.toString=function(){return"[native code]"};var un=globalThis,es=un.caches;if(es){let n=es.open;un.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete un.caches.default,Object.freeze(un.caches)}var ts=new Map,Fr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,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((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},lt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ts.get(e);r||(r=new Fr(t),ts.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var jr="__zuplo-expiry-header",dt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#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 t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(jr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.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(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(jr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.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 t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(jr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var le=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new lt(r),this.#n=new dt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;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,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var ns="zuplo-request-id",nt="zp-rid",Br="zp-body-removed",rt="cf-ray",rs="x-real-ip",zr="cf-ipcity",Vr="cf-ipcontinent",Gr="cf-ipcountry",Wr="cf-iplongitude",Jr="cf-iplatitude",os="cf-region",is="cf-region-code",ss="cf-metro-code",as="cf-postal-code",us="cf-timezone",cs="zp-ipcity",ls="zp-ipcontinent",ds="zp-ipcountry",ps="zp-iplongitude",ms="zp-iplatitude",gs="true-client-ip",Kr="zp-asn",Yr="zp-asorg",Xr="zp-colo",Qr="zp-postalcode",eo="zp-metrocode",to="zp-region",no="zp-regioncode",ro="zp-timezone",fs=[zr,Vr,Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro],hs=["zp-","cf-"],ys=[nt,rt,Br];var Ut="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",cn="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Ht="system-logger";var Qs=require("@opentelemetry/api"),ea=Qe(Be());var fn=require("@opentelemetry/api");var Ge=require("@opentelemetry/api");var bs=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ws(n){bs=n}i(ws,"setTelemetryInitFunction");var Rs=i(n=>bs(n),"proxyHandler");var ze=class{static{i(this,"RuntimePlugin")}},He=class extends ze{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},ln=class extends He{static{i(this,"MeteringPlugin")}},pt=class extends ze{static{i(this,"TelemetryPlugin")}};var Zt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,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&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new _("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ve=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Zt.problemResponseFormat(e,t,r)}};function dn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&dn(t)}return Object.freeze(n)}i(dn,"deepFreeze");var ne=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return dn(this.#e)}get params(){return dn(this.#t)}user};var qt={},Ze=[],oo=[],io=[],so=[];var pn={addPlugin(n){Ze.push(n)},addRequestHook(n){oo.push(n)},addResponseSendingHook(n){io.push(n)},addResponseSendingFinalHook(n){so.push(n)}},Es=i(async(n,e)=>{if(oo.length===0)return n;let t=Ge.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of oo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ne||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Ge.SpanStatusCode.ERROR}),l}});if(a instanceof ne)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Is=i(async(n,e,t)=>{if(io.length===0)return n;let r=Ge.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of io)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Ge.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),xs=i(async(n,e,t)=>{if(so.length===0)return;let r=Ge.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of so)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Ge.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ps=!1;async function Ts(n=()=>Promise.resolve()){if(!Ps){await n(pn),qt.value=pn;for(let e of Ze)if(e instanceof pt){let{requestHandlerProxy:t}=e.instrument({accountName:g.instance.build.ACCOUNT_NAME,projectName:g.instance.build.PROJECT_NAME,buildId:g.instance.build.BUILD_ID,zuploVersion:g.instance.build.ZUPLO_VERSION,compatibilityDate:g.instance.build.COMPATIBILITY_DATE,instanceId:g.instance.instanceId,environmentType:g.instance.loggingEnvironmentType,environmentStage:g.instance.loggingEnvironmentStage,deploymentName:g.instance.deploymentName});ws(t)}for(let e of Ze)e instanceof He&&await e.initialize(pn);Zt.setProblemResponseFormat(pn.problemResponseFormat),Ps=!0}}i(Ts,"initializeRuntime");var mn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function gn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(mn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(mn.Json)||!e?JSON.stringify(n):n}i(gn,"serialize");function mt(n){return fe.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(fe.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(mt,"isSystemRoute");var de=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>fn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:fn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let O=a.pop();return O?O(o,s,t,u):await this.#e(async F=>{let Z=await r(F,s);return Rl(Z)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(mt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gt(o,l);s.dispatchEvent(p);let f=he.getContextExtensions(s),h=f.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await f.onResponseSending(A,h,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Is(A,h,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new ft(o,A));try{await f.onResponseSendingFinal(l,h,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await xs(l,h,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Rl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(gn(n),{headers:{"content-type":"application/json"}})}i(Rl,"resultToResponse");var $t=(b=>(b[b.CONTINUE=100]="CONTINUE",b[b.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",b[b.PROCESSING=102]="PROCESSING",b[b.EARLY_HINTS=103]="EARLY_HINTS",b[b.OK=200]="OK",b[b.CREATED=201]="CREATED",b[b.ACCEPTED=202]="ACCEPTED",b[b.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",b[b.NO_CONTENT=204]="NO_CONTENT",b[b.RESET_CONTENT=205]="RESET_CONTENT",b[b.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",b[b.MULTI_STATUS=207]="MULTI_STATUS",b[b.ALREADY_REPORTED=208]="ALREADY_REPORTED",b[b.IM_USED=226]="IM_USED",b[b.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",b[b.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",b[b.FOUND=302]="FOUND",b[b.SEE_OTHER=303]="SEE_OTHER",b[b.NOT_MODIFIED=304]="NOT_MODIFIED",b[b.USE_PROXY=305]="USE_PROXY",b[b.SWITCH_PROXY=306]="SWITCH_PROXY",b[b.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",b[b.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",b[b.BAD_REQUEST=400]="BAD_REQUEST",b[b.UNAUTHORIZED=401]="UNAUTHORIZED",b[b.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",b[b.FORBIDDEN=403]="FORBIDDEN",b[b.NOT_FOUND=404]="NOT_FOUND",b[b.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",b[b.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",b[b.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",b[b.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",b[b.CONFLICT=409]="CONFLICT",b[b.GONE=410]="GONE",b[b.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",b[b.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",b[b.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",b[b.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",b[b.URI_TOO_LONG=414]="URI_TOO_LONG",b[b.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",b[b.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",b[b.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",b[b.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",b[b.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",b[b.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",b[b.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",b[b.LOCKED=423]="LOCKED",b[b.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",b[b.TOO_EARLY=425]="TOO_EARLY",b[b.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",b[b.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",b[b.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",b[b.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",b[b.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",b[b.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",b[b.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",b[b.BAD_GATEWAY=502]="BAD_GATEWAY",b[b.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",b[b.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",b[b.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",b[b.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",b[b.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",b[b.LOOP_DETECTED=508]="LOOP_DETECTED",b[b.NOT_EXTENDED=510]="NOT_EXTENDED",b[b.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",b))($t||{}),vs={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 Pl={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"},hn=Pl;function El(n){return`${new URL(n.url).pathname}`}i(El,"instance");function Il(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(rt);return r&&(t.rayId=r),t}i(Il,"trace");var xl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:El(e),trace:Il(e,t),...r},additionalHeaders:o,statusText:hn[n.status]}),"merge"),ao=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ve.format(e,t,r):Ve.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:vs[e],...t}}},x=class extends ao{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=xl(this.getProblemFromStatus(e),t,r,o,s);return Ve.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var We=class extends ze{static{i(this,"MetricsPlugin")}};var te=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new X(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,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(t=>{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(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var yn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=g.instance.loggingId,this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,te.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{loggingId:t,remoteLogURL:r,deploymentName:o,systemUserAgent:s}=g.instance,a=`${r}/v1/runtime/metrics`,u=e.map(l=>{let d=Object.assign({},l);return delete d.requestContentLength,delete d.responseContentLength,d.deploymentName=o,d.projectId=t,d}),c=await q.fetch(a,{method:"POST",body:JSON.stringify(u),headers:{"content-type":"application/json","zp-dn":o??"unknown","user-agent":s}});if(!c.ok){let l=await c.text();te.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,l)}}};var ae=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Ft.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ft={name:"__system-no-version",pathPrefix:""};var ye=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(rt)??void 0,c=n.headers.get(gs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ae&&(d=e.route.systemRouteName);let p=he.getContextExtensions(e).latestRequest,f={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.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:n.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:g.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new yn(e)),Ze.forEach(A=>{if(A instanceof We){let P=A.getTransport();h.push(P)}}),h.forEach(A=>{A.pushMetrics(f,e)}),a},"metricsProcessor");var Ne=(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))(Ne||{});var uo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=g.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new de({processors:[ye],handler:t,gateway:e}),o=new ae({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Tl}=Object.prototype,{propertyIsEnumerable:vl}=Object.prototype;function co(n){return Tl.call(n)}i(co,"toString");function Ie(n){return typeof n=="string"}i(Ie,"isString");function ht(n){return Ie(n)&&n!==""}i(ht,"isNonEmptyString");function Ss(n){return co(n)==="[object RegExp]"}i(Ss,"isRegexp");function Os(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>vl.call(n,e))]}i(Os,"getOwnEnumerableKeys");function ot(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ot,"isObject");function lo(n){return typeof n=="number"&&!isNaN(n)}i(lo,"isNumber");function po(n){return n===!0||n===!1}i(po,"isBoolean");function Cs(n){return typeof n>"u"}i(Cs,"isUndefined");function As(n){return Cs(n)||n===null}i(As,"isUndefinedOrNull");function jt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(jt,"isErrorLike");var _s=new Map;function yt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=_s.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return _s.set(n,r),r}i(yt,"statusCodesStringToNumberArray");function it(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new _(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(it,"getValueFromRequestUser");function Ls(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new _(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new _(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(Ls,"selectPropertyUsingJsonPath");function st(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(st,"parseValueToStringArray");function ks(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!ot(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ht(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!lo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!po(t.allowCredentials))throw new m("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=mo(t,"allowedHeaders"),o=mo(t,"allowedMethods"),s=mo(t,"exposeHeaders"),a;try{a=st(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ks,"parseCorsPolicies");function mo(n,e){let t;if(n[e]!==void 0)try{t=st(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(mo,"parseOptionalProperty");var bn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),wn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var go=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let h=f.routeConfiguration,A=Sl(l,d,p,h,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new de({processors:[ye],handler:r,gateway:e}),s=new ae({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Sl=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=bn(a.allowedOrigins,t);return u?{isValid:!0,headers:wn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ns=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new de({processors:[ye],handler:t,gateway:e}),o=new ae({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var fo=new ae({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ms=i((n,e)=>{let t=i(async(o,s)=>{let a=qt.value?.notFoundHandler;if(a){let u=he.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new de({processors:[ye],handler:t,gateway:e});n.addRoute(fo,r.execute)},"registerNotMatchedHandler");var Ol=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ds=i(n=>{Ol.forEach(e=>n.delete(e))},"stripCorsHeaders"),Rn=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Ds(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new X(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Cl(o,t.routeData.corsPolicies),u=Al(n,a),c=new Headers(s.headers);return Ds(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Cl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Al=i((n,e)=>{let t=bn(e.allowedOrigins,n.headers.get("origin"));return t?wn(e,t):{}},"getCorsHeaders");var ho=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:g.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new de({processors:[Rn],handler:t,gateway:e}),o=new ae({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var bt=require("@opentelemetry/api");var Ae={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Pn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},be=class extends Pn{static{i(this,"InboundPolicy")}},qe=class extends Pn{static{i(this,"OutboundPolicy")}};var wo=class extends be{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Ro=class extends qe{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},yo=new Map;function Bt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!yo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof be)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wo(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);yo.set(a.name,c)}),t.map(s=>{let a=yo.get(s);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}i(Bt,"getInboundPolicyInstances");var bo=new Map;function _l(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!bo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof qe)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ro(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);bo.set(s.name,u)}),t.map(o=>{let s=bo.get(o);if(s===void 0)throw new _("Internal error. Policy not found in cache.");return s})}i(_l,"getOutboundPolicyInstances");var Po=i(n=>async(e,t)=>{let r=he.getContextExtensions(t),o=bt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof ne||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:bt.SpanStatusCode.ERROR}),d.recordException(f),f}});if(l instanceof ne)u=l;else if(l instanceof Request)u=new ne(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ll=i(n=>async(e,t,r)=>{let o=bt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Ae.PolicyName,c.policyName),d.setAttribute(Ae.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:bt.SpanStatusCode.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),En=i(async(n,e,t,r)=>{let o=Bt(e.route,t.routeData.policies),s=_l(e.route,t.routeData.policies);return Hs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Us({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Hs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Us,"createInternalPolicyProcessor");async function Hs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Po(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ll(r),d;return g.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(Hs,"executePolicyProcessor");function Zs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||kl,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Nl(l,o)}s=u+1}return t}i(Zs,"parse");function kl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(kl,"decode");function Nl(n,e){try{return e(n)}catch{return n}}i(Nl,"tryDecode");function qs(n,e){try{let t=/v\d+(-\d+)?/g,o=Zs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(qs,"devPortalBaseURL");var $s="/__zuplo/dev-portal",Ml="dev-portal-id",Dl="dev-portal-host",Ul="zp-account",Hl="zp-project",Zl="dev-portal-build",ql=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(pl,"reduceToSingleString")});var Gi=Dt(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.format=void 0;var ml=qi(),gl=Vi(),fl=i((n,...e)=>(0,ml.format)(gl.inspect,n,e),"format");on.format=fl});var ze=Dt(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.debug=Be.withoutEnv=Be.Debugger=void 0;var hl=Zi(),yl=Gi(),sn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,yl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Be.Debugger=sn;var an=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Wi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Wi,"extract");var Ut;function bl(n){n||(n=[]),typeof n=="string"&&(n=Wi(n)),Ut=new an(n)}i(bl,"withoutEnv");Be.withoutEnv=bl;function wl(n){let e=globalThis.DEBUG;Ut||(Ut=new an(Wi(e)));let t=new sn(Ut,n);return Ut.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(wl,"debug");Be.debug=wl});var Sp={};pc(Sp,{AWSLoggingPlugin:()=>Gn,AmberfloMeteringInboundPolicy:()=>Za,AmberfloMeteringPolicy:()=>er,ApiAuthKeyInboundPolicy:()=>$a,ApiKeyInboundPolicy:()=>nr,AuditLogDataStaxProvider:()=>Kn,AuditLogPlugin:()=>Yn,Auth0JwtInboundPolicy:()=>za,AwsLambdaHandlerExtensions:()=>wa,AxiomaticsAuthZInboundPolicy:()=>ir,BackgroundDispatcher:()=>vr,BackgroundLoader:()=>Sr,BasicAuthInboundPolicy:()=>Va,BasicRateLimitInboundPolicy:()=>wi,BatchDispatch:()=>X,BrownoutInboundPolicy:()=>ur,CachingInboundPolicy:()=>Wa,ChangeMethodInboundPolicy:()=>Ja,ClearHeadersInboundPolicy:()=>Ka,ClearHeadersOutboundPolicy:()=>Ya,ClerkJwtInboundPolicy:()=>Xa,CognitoJwtInboundPolicy:()=>Qa,CompositeInboundPolicy:()=>eu,ConfigurationError:()=>m,ContentTypes:()=>fn,ContextData:()=>Ce,CryptoBeta:()=>Cr,CurityPhantomTokenInboundPolicy:()=>tu,DataDogLoggingPlugin:()=>Ln,DataDogMetricsPlugin:()=>Wn,DynaTraceLoggingPlugin:()=>jn,DynatraceMetricsPlugin:()=>Jn,FirebaseJwtInboundPolicy:()=>nu,FormDataToJsonInboundPolicy:()=>ru,GeoFilterInboundPolicy:()=>ou,GoogleCloudLoggingPlugin:()=>Cn,Handler:()=>Fn,HttpProblems:()=>T,HttpStatusCode:()=>$t,InboundPolicy:()=>we,JWTScopeValidationInboundPolicy:()=>iu,KeyValueStore:()=>_r,LokiLoggingPlugin:()=>Bn,LookupResult:()=>Pt,MemoryZoneReadThroughCache:()=>de,MockApiInboundPolicy:()=>au,MoesifInboundPolicy:()=>mu,MonetizationInboundPolicy:()=>lr,OktaJwtInboundPolicy:()=>bu,OpenIdJwtInboundPolicy:()=>fe,OutboundPolicy:()=>Fe,ProblemResponseFormatter:()=>Ge,PropelAuthJwtInboundPolicy:()=>Ru,RateLimitInboundPolicy:()=>wi,ReadmeMetricsInboundPolicy:()=>Ou,RemoveHeadersInboundPolicy:()=>Cu,RemoveHeadersOutboundPolicy:()=>Au,RemoveQueryParamsInboundPolicy:()=>_u,ReplaceStringOutboundPolicy:()=>Lu,RequestSizeLimitInboundPolicy:()=>Nu,RequestValidationInboundPolicy:()=>Ei,RequireOriginInboundPolicy:()=>$u,ResponseSendingEvent:()=>ft,ResponseSentEvent:()=>ht,Router:()=>Et,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Zt,SchemaBasedRequestValidation:()=>Fu,SemanticAttributes:()=>_e,ServiceProviderImpl:()=>Tr,SetBodyInboundPolicy:()=>ju,SetHeadersInboundPolicy:()=>Bu,SetHeadersOutboundPolicy:()=>zu,SetQueryParamsInboundPolicy:()=>Vu,SetStatusOutboundPolicy:()=>Gu,SleepInboundPolicy:()=>Wu,StripeMonetizationPlugin:()=>ai,StripeWebhookVerificationInboundPolicy:()=>vt,SumoLogicLoggingPlugin:()=>zn,SupabaseJwtInboundPolicy:()=>Ju,SystemRouteName:()=>Me,TelemetryPlugin:()=>mt,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ku,UpstreamFirebaseAdminAuthInboundPolicy:()=>Xu,UpstreamFirebaseUserAuthInboundPolicy:()=>Qu,UpstreamGcpJwtInboundPolicy:()=>ec,UpstreamGcpServiceAuthInboundPolicy:()=>nc,VMWareLogInsightLoggingPlugin:()=>Vn,ValidateJsonSchemaInbound:()=>rc,XmlToJsonOutboundPolicy:()=>xr,ZoneCache:()=>pt,ZuploRequest:()=>re,awsLambdaHandler:()=>Ra,environment:()=>Re,getIdForParameterSchema:()=>Er,getIdForRefSchema:()=>Du,getIdForRequestBodySchema:()=>Ir,getRawOperationDataIdentifierName:()=>Mu,httpStatuses:()=>bn,openApiSpecHandler:()=>Pa,redirectHandler:()=>Ea,sanitizedIdentifierName:()=>Qe,serialize:()=>hn,setMoesifContext:()=>pu,trackFeature:()=>f,urlForwardHandler:()=>Ia,urlRewriteHandler:()=>xa,webSocketHandler:()=>Ta,webSocketPipelineHandler:()=>Oa});module.exports=mc(Sp);var Xi=et(ze());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},un=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var $r="2024-03-14",Ji=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Ki(){return new g({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:$r,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Ji[$r]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(Ki,"getMockEnvironment");var g=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Ki()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var nt=(0,Xi.debug)("zuplo:runtime:external-service");function Rl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=g.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Rl,"getServiceAuth");async function Qi(n,e){let t=Rl();if(t)if(nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(g.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{nt("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Pl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw nt("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);nt(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw nt("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw nt("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(Qi,"externalServiceHandler");async function Pl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=El(r);nt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Yi(`${s}-${o}`),l=await Yi(`${s}-${a}-${u}`);return`${c}.${l}`}i(Pl,"hashServiceName");async function Yi(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Yi,"hashSegment");function El(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(El,"sanitizeEnvironmentType");var ts=new Map;ts.set("service:",Qi);var es=globalThis.fetch;function jr(n,e){let t=Il(e);if(typeof n=="string"){let r=new URL(n),o=ts.get(r.protocol);return o?o(n,t):es(n,t)}else return es(n,t)}i(jr,"internalFetch");globalThis.fetch=jr;var Il=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var xl={fetch:jr},F=xl;Function.prototype.toString=function(){return"[native code]"};var cn=globalThis,ns=cn.caches;if(ns){let n=ns.open;cn.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete cn.caches.default,Object.freeze(cn.caches)}var rs=new Map,Br=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,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((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},dt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=rs.get(e);r||(r=new Br(t),rs.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var zr="__zuplo-expiry-header",pt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#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 t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(zr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.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(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(zr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.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 t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(zr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var de=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new dt(r),this.#n=new pt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;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,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var os="zuplo-request-id",rt="zp-rid",Vr="zp-body-removed",ot="cf-ray",is="x-real-ip",Gr="cf-ipcity",Wr="cf-ipcontinent",Jr="cf-ipcountry",Kr="cf-iplongitude",Yr="cf-iplatitude",ss="cf-region",as="cf-region-code",us="cf-metro-code",cs="cf-postal-code",ls="cf-timezone",ds="zp-ipcity",ps="zp-ipcontinent",ms="zp-ipcountry",gs="zp-iplongitude",fs="zp-iplatitude",hs="true-client-ip",Xr="zp-asn",Qr="zp-asorg",eo="zp-colo",to="zp-postalcode",no="zp-metrocode",ro="zp-region",oo="zp-regioncode",io="zp-timezone",ys=[Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro,oo,io],bs=["zp-","cf-"],ws=[rt,ot,Vr];var Ht="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",ln="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Zt="system-logger";var oa=require("@opentelemetry/api"),ia=et(ze());var yn=require("@opentelemetry/api");var We=require("@opentelemetry/api");var Rs=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ps(n){Rs=n}i(Ps,"setTelemetryInitFunction");var Es=i(n=>Rs(n),"proxyHandler");var Ve=class{static{i(this,"RuntimePlugin")}},Ze=class extends Ve{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},dn=class extends Ze{static{i(this,"MeteringPlugin")}},mt=class extends Ve{static{i(this,"TelemetryPlugin")}};var pn=new Set,Is=new Set;function f(n){Is.has(n)||(Is.add(n),pn.add(n))}i(f,"trackFeature");function xs(){let n=[...pn];return pn.clear(),n}i(xs,"getUnsentFeatures");function Ts(n){for(let e of n)pn.add(e)}i(Ts,"restoreFeatures");var qt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,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&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ge=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await qt.problemResponseFormat(e,t,r)}};function mn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&mn(t)}return Object.freeze(n)}i(mn,"deepFreeze");var re=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return mn(this.#e)}get params(){return mn(this.#t)}user};var Ft={},qe=[],so=[],ao=[],uo=[];var gn={addPlugin(n){qe.push(n)},addRequestHook(n){so.push(n)},addResponseSendingHook(n){ao.push(n)},addResponseSendingFinalHook(n){uo.push(n)}},Ss=i(async(n,e)=>{if(so.length===0)return n;let t=We.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of so){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:We.SpanStatusCode.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Os=i(async(n,e,t)=>{if(ao.length===0)return n;let r=We.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of ao)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:We.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Cs=i(async(n,e,t)=>{if(uo.length===0)return;let r=We.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of uo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:We.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),vs=!1;async function As(n){if(!vs){n&&(f("runtime.extensions"),await n(gn)),Ft.value=gn;for(let e of qe)if(e instanceof mt){let{requestHandlerProxy:t}=e.instrument({accountName:g.instance.build.ACCOUNT_NAME,projectName:g.instance.build.PROJECT_NAME,buildId:g.instance.build.BUILD_ID,zuploVersion:g.instance.build.ZUPLO_VERSION,compatibilityDate:g.instance.build.COMPATIBILITY_DATE,instanceId:g.instance.instanceId,environmentType:g.instance.loggingEnvironmentType,environmentStage:g.instance.loggingEnvironmentStage,deploymentName:g.instance.deploymentName});Ps(t)}for(let e of qe)e instanceof Ze&&await e.initialize(gn);qt.setProblemResponseFormat(gn.problemResponseFormat),vs=!0}}i(As,"initializeRuntime");var fn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function hn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(fn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(fn.Json)||!e?JSON.stringify(n):n}i(hn,"serialize");function gt(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>yn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:yn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async E=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async j=>{let q=await r(j,s);return Tl(q)},t)(E,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ft(o,l);s.dispatchEvent(p);let h=ye.getContextExtensions(s),y=h.latestRequest,_;try{_=await p.mutableResponse}catch(E){return s.log.error(E),t.errorHandler(o,s,E)}try{_=await h.onResponseSending(_,y,s)}catch(E){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${E.message}'`,E),t.errorHandler(o,s,E)}try{_=await Os(_,y,s)}catch(E){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${E.message}'`,E),t.errorHandler(o,s,E)}s.dispatchEvent(new ht(o,_));try{await h.onResponseSendingFinal(l,y,s)}catch(E){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${E.message}'`,E),E}try{await Cs(l,y,s)}catch(E){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${E.message}'`,E),E}return _}};function Tl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(hn(n),{headers:{"content-type":"application/json"}})}i(Tl,"resultToResponse");var $t=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))($t||{}),_s={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 vl={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"},bn=vl;function Sl(n){return`${new URL(n.url).pathname}`}i(Sl,"instance");function Ol(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(Ol,"trace");var Cl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Sl(e),trace:Ol(e,t),...r},additionalHeaders:o,statusText:bn[n.status]}),"merge"),co=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ge.format(e,t,r):Ge.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:_s[e],...t}}},T=class extends co{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Cl(this.getProblemFromStatus(e),t,r,o,s);return Ge.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Je=class extends Ve{static{i(this,"MetricsPlugin")}};var ne=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new Q(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var X=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,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(t=>{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(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var wn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=g.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,ne.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=g.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=g.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=xs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":g.instance.deploymentName??"unknown","user-agent":g.instance.systemUserAgent}});if(!l.ok){let d=await l.text();ne.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ts(u)}}};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=jt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},jt={name:"__system-no-version",pathPrefix:""};var be=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(hs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.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:n.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:g.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new wn(e)),qe.forEach(_=>{if(_ instanceof Je){let E=_.getTransport();y.push(E)}}),y.forEach(_=>{_.pushMetrics(h,e)}),a},"metricsProcessor");var Me=(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))(Me||{});var lo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=g.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&ne.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new pe({processors:[be],handler:t,gateway:e}),o=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Al}=Object.prototype,{propertyIsEnumerable:_l}=Object.prototype;function po(n){return Al.call(n)}i(po,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function yt(n){return xe(n)&&n!==""}i(yt,"isNonEmptyString");function Ls(n){return po(n)==="[object RegExp]"}i(Ls,"isRegexp");function ks(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>_l.call(n,e))]}i(ks,"getOwnEnumerableKeys");function it(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(it,"isObject");function mo(n){return typeof n=="number"&&!isNaN(n)}i(mo,"isNumber");function go(n){return n===!0||n===!1}i(go,"isBoolean");function Ns(n){return typeof n>"u"}i(Ns,"isUndefined");function Ms(n){return Ns(n)||n===null}i(Ms,"isUndefinedOrNull");function Bt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Bt,"isErrorLike");var Ds=new Map;function bt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Ds.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ds.set(n,r),r}i(bt,"statusCodesStringToNumberArray");function st(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(st,"getValueFromRequestUser");function Us(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new L(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new L(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(Us,"selectPropertyUsingJsonPath");function at(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(at,"parseValueToStringArray");function Hs(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!it(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!yt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!mo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!go(t.allowCredentials))throw new m("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=fo(t,"allowedHeaders"),o=fo(t,"allowedMethods"),s=fo(t,"exposeHeaders"),a;try{a=at(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Hs,"parseCorsPolicies");function fo(n,e){let t;if(n[e]!==void 0)try{t=at(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(fo,"parseOptionalProperty");var Rn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Pn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var ho=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return T.notFound(a,u);let y=h.routeConfiguration,_=Ll(l,d,p,y,t);return _.isValid?new Response(void 0,{status:200,statusText:"OK",headers:_.headers}):(_.error&&u.log.warn(_.error),T.notFound(a,u))},"optionsHandler"),o=new pe({processors:[be],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Ll=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Rn(a.allowedOrigins,t);return u?{isValid:!0,headers:Pn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Zs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[be],handler:t,gateway:e}),o=new ue({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var yo=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),qs=i((n,e)=>{let t=i(async(o,s)=>{let a=Ft.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new pe({processors:[be],handler:t,gateway:e});n.addRoute(yo,r.execute)},"registerNotMatchedHandler");var kl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Fs=i(n=>{kl.forEach(e=>n.delete(e))},"stripCorsHeaders"),En=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Fs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Nl(o,t.routeData.corsPolicies),u=Ml(n,a),c=new Headers(s.headers);return Fs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Nl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ml=i((n,e)=>{let t=Rn(e.allowedOrigins,n.headers.get("origin"));return t?Pn(e,t):{}},"getCorsHeaders");var bo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:g.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[En],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var wt=require("@opentelemetry/api");var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var In=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},we=class extends In{static{i(this,"InboundPolicy")}},Fe=class extends In{static{i(this,"OutboundPolicy")}};var Po=class extends we{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Eo=class extends Fe{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},wo=new Map;function zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!wo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof we)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Po(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);wo.set(a.name,c)}),t.map(s=>{let a=wo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(zt,"getInboundPolicyInstances");var Ro=new Map;function Dl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Ro.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Eo(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Ro.set(s.name,u)}),t.map(o=>{let s=Ro.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Dl,"getOutboundPolicyInstances");var Io=i(n=>async(e,t)=>{let r=ye.getContextExtensions(t),o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof re||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:wt.SpanStatusCode.ERROR}),d.recordException(h),h}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ul=i(n=>async(e,t,r)=>{let o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:wt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),xn=i(async(n,e,t,r)=>{let o=zt(e.route,t.routeData.policies),s=Dl(e.route,t.routeData.policies);return js({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function $s({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>js({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i($s,"createInternalPolicyProcessor");async function js({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Io(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ul(r),d;return g.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(js,"executePolicyProcessor");function Bs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Hl,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Zl(l,o)}s=u+1}return t}i(Bs,"parse");function Hl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Hl,"decode");function Zl(n,e){try{return e(n)}catch{return n}}i(Zl,"tryDecode");function zs(n,e){try{let t=/v\d+(-\d+)?/g,o=Bs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(zs,"devPortalBaseURL");var Vs="/__zuplo/dev-portal",ql="dev-portal-id",Fl="dev-portal-host",$l="zp-account",jl="zp-project",Bl="dev-portal-build",zl=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -46,30 +46,30 @@
|
|
|
46
46
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
47
47
|
</body>
|
|
48
48
|
</html>
|
|
49
|
-
`,
|
|
50
|
-
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(
|
|
51
|
-
`)}i(
|
|
49
|
+
`,Gs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=g.instance.deploymentName,o=g.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(g.instance.isLocalDevelopment)return new Response(zl,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=zs(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:_,body:E}=c;return g.instance.build.ACCOUNT_NAME&&y.set($l,g.instance.build.ACCOUNT_NAME),g.instance.build.PROJECT_NAME&&y.set(jl,g.instance.build.PROJECT_NAME),y.set(ql,r),y.set(Fl,d.host),y.set(Bl,g.instance.build.BUILD_ID),await F.fetch(h.toString(),{headers:y,method:_,body:E,redirect:"manual"})},"devPortalRoute"),a=new pe({processors:[be,xn],handler:s,gateway:e}),u=new ue({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Ws=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Vs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new pe({processors:[be],handler:r,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Vs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ta=et(ze());var xo=0,Vt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){xo>=Number.MAX_SAFE_INTEGER&&(xo=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:xo++};this.#t[e](u,a)}};var me=class extends Ve{static{i(this,"LogPlugin")}};var Tn=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Gt=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Vl=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Gl=new Map(Vl);var Wl=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],To=Symbol(".toJSON was called"),Jl=i(n=>{n[To]=!0;let e=n.toJSON();return delete n[To],e},"toJSON"),Kl=i(n=>Gl.get(n)??Error,"getErrorConstructor"),Js=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Bt(n)){let l=Kl(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[To]!==!0)return Jl(n);let c=i(l=>Js({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Wl)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Bt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Pe(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Js({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Pe,"serializeError");var Yl=/file:\/\/\/(.*?)\/dist\//g,Xl="at async Event.respondWith";function Ks(n){return typeof n!="string"?n:n.split(`
|
|
50
|
+
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Yl,"").replaceAll(Xl,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
51
|
+
`)}i(Ks,"cleanStack");function vn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
52
52
|
`,newlineOrSpace:`
|
|
53
|
-
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let
|
|
54
|
-
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||
|
|
55
|
-
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(
|
|
56
|
-
`)}i(Vs,"messagesToMultilineText");function $e(n){return typeof n=="string"?n:JSON.stringify(n)}i($e,"stringifyNonString");function xo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?co(n):"unknown"}i(xo,"stringifyNonStringToText");var Tn=require("jose");async function Pe(n,e,t){for(let r=0;r<=n.retries;r++){let o=q.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(Pe,"fetchRetry");async function Me({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Tn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Me,"getTokenFromGcpServiceAccount");async function Gs(n,e,t){return Ws(n,{token:e,returnSecureToken:!0},t)}i(Gs,"exchangeFirebaseJwtForIdToken");async function vn(n,e,t){return Ws(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(vn,"exchangeGgpJwtForIdToken");async function Ws(n,e,t){let r=await Pe(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new _({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Ws,"fetchToken");var xe=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,Tn.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Sn=class extends pe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Gt(this.options)}},Wl="https://logging.googleapis.com/v2/entries:write?alt=json",To={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Gt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=g.instance.loggingEnvironmentType,this.#i=g.instance.loggingEnvironmentStage,this.#r=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await xe.init(this.#e)}log(e,t){if(!this.#t)throw new X("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Je(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:To[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=wt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await xe.init(this.#e));let t=await Me({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await q.fetch(Wl,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new Y("google-log-transport",1,this.dispatchFunction)};var On="gcp";function Cn(n){let e={allMessages:Je(n.messages)},t="zuplo-production",r=wt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:To[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(Cn,"gcpLogFormat");var Wt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===On){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Cn(e)])}else this.#e.log(JSON.stringify(e))}};var An=class extends pe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Jt(this.options)}},vo="__ddtags",So="__ddattr",Oo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Jl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Oo(r)):t.push(`${Oo(r)}:${Oo(o.toString())}`)}),t.join(",")},"formatTags"),Jt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[vo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(h=>h[vo]!==void 0);a>-1&&(Object.assign(r,s[a][vo]),s.splice(a,1));let u={},c=t.custom[So];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(h=>h[So]!==void 0);l>-1&&(Object.assign(u,s[l][So]),s.splice(l,1));let d=Je(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:wt(d),service:e.loggingId,ddtags:Jl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await q.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Kt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===On){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Cn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Kl=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await q.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Je(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),_n,Ln=class{static{i(this,"RemoteLogTransport")}constructor(e){_n||(_n=new Y("remote-log-transport",1,Kl(e)))}log(e,t){_n.enqueue(e),t.waitUntil(_n.waitUntilFlushed())}};var Yl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Js=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Yl[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Xl=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Js(t,r);try{await q.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),kn,Nn=class{static{i(this,"UnifiedLogTransport")}constructor(e){kn||(kn=new Y("unified-log-transport",1,Xl(e)))}async log(e,t){kn.enqueue(e),t.waitUntil(kn.waitUntilFlushed())}};var Co=(0,Ks.debug)("zuplo:logging"),Mn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(g.instance,e),r=await n.setupUserCoreLogger(g.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Co("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Ht);return s?o.push(new Kt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Wt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Nn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new zt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Co("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Ht);if(a&&a.captureUserLogs===!0?r.push(new Kt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Wt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Ln({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Gt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Jt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ze.forEach(u=>{u instanceof pe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new zt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Co("Gateway.createRequestLoggers");let a=new In(r,o,s),u=new Vt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Vt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var at=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Ao=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Rt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_o=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Pt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof at||e instanceof ae))throw new X("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Ao(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new _o(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Rt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Rt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Lo;function Ys(n){Lo=n}i(Ys,"setGlobalZuploEventContext");function Dn(){if(Lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Lo}i(Dn,"getGlobalZuploEventContext");function Xs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);hs.includes(o.toLowerCase())&&!ys.includes(r.toLowerCase())&&t.delete(r)}t.delete(rs)}else fs.forEach(r=>{t.delete(r)});return t}i(Xs,"normalizeIncomingRequestHeaders");var De=(0,ea.debug)("zuplo:runtime"),Ql=i(n=>{let e=n.findIndex(t=>t.name===Ft.name);return e>-1?[...n.splice(e),Ft]:[...n,Ft]},"setupSystemNoVersion"),fe=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),Ae,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await Mn.init(r),a=e(),u={...a,corsPolicies:ks(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new X("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new X("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[En,Rn,ye];#o;setupRoutes=()=>{De("Gateway.setupRoutes");let e=this.routeData,t=Ql(e.versions),r=new Pt(t);if(e.routes.length===0)return uo(r,this),ho(r,this),go(r,this),Ns(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(js(r,this),Fs(r,this)),uo(r,this),ho(r,this),go(r,this);for(let s of Ze)s instanceof He&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new de({processors:this.#r,handler:a,gateway:this}),c=new at(s);r.addRoute(c,u.execute)}),Ms(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof _&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Re(r.cause);"stack"in s&&(s.stack=zs(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;Ys(r);let a=Xs({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(nt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let F=new Headers(u.headers);F.set(Br,"true"),u=new Request(u,{headers:F,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),f=p.pathname,h=this.#n.lookup(u.method,f);if(!h)throw new X(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let A=new Un(e.headers),P=new ne(u,{params:h.params}),O=new Hn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=h.routeConfiguration.raw();Qs.trace.getActiveSpan()?.setAttributes({"http.route":O.route.path??O.route.pathPattern,"cloud.region":O.incomingRequestProperties.colo,[Ae.RoutePathPattern]:O.route.pathPattern,[Ae.RouteOperationId]:H.operationId,[Ae.RouteTrace]:H["x-zuplo-trace"],[Ae.RouteSystem]:mt(p)?!0:void 0});let k=he.initialize(O,P);if(h.routeConfiguration===fo&&qt.value?.notFoundHandler!==void 0){let F=this.#n.lookupByPathOnly(f);k.pathOnlyMatches=F.map(Z=>Z.routeConfiguration).filter(Z=>Z instanceof at)}try{if(te.addLogger(O,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!mt(p):!p.pathname.startsWith("/__zuplo")){let R=await Es(P,O);if(R instanceof Response)return R;{let M=he.getContextExtensions(O);P=R,M.latestRequest=P}}mt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let F=h.executableHandler;ed(F,h,u),De("Gateway.handleRequest - call user handler");let Z=await F(P,O);if(De("Gateway.handleRequest - user handler"),!(Z instanceof Response))throw new _(`Invalid Response type from the request handler: ${typeof Z}`);if(Z.bodyUsed)throw new _("The response object has already been used. Return a new response instead.");let j;if(Z.headers.get(nt)===null&&!Z.webSocket){let R=new Headers(Z.headers);R.set(nt,o),j=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:R,cf:Z.cf})}else j=Z;return j}catch(F){return De("Gateway - error executing handler",F),F instanceof _?(l.error(F),d.warn(F)):d.error(F),await this.#i(P,O,F)}}};function ed(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(ed,"checkHandler");var ta=i(async(n,e,t)=>{let r=fe.instance.routeData.policies,o=Bt([n],r);if(o.length===0)throw new _(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Un=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Kr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Yr)??void 0}get city(){return this.#e.get(zr)??this.#e.get(cs)??void 0}get continent(){return this.#e.get(Vr)??this.#e.get(ls)??void 0}get country(){return this.#e.get(Gr)??this.#e.get(ds)??void 0}get latitude(){return this.#e.get(Jr)??this.#e.get(ms)??void 0}get longitude(){return this.#e.get(Wr)??this.#e.get(ps)??void 0}get colo(){return this.#e.get(Xr)??void 0}get postalCode(){return this.#e.get(as)??this.#e.get(Qr)??void 0}get metroCode(){return this.#e.get(ss)??this.#e.get(eo)??void 0}get region(){return this.#e.get(os)??this.#e.get(to)??void 0}get regionCode(){return this.#e.get(is)??this.#e.get(no)??void 0}get timezone(){return this.#e.get(us)??this.#e.get(ro)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},gt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ft=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},he=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new _(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},Hn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>ta(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{he.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{he.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var Oe=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var td=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function nd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!td.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(nd,"isRestrictedEnvVariableName");function rd(n){return!!n.startsWith("ZUPLO_")}i(rd,"isZuploReadableEnvVariableName");var we=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return g.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return g.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return g.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return g.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return g.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return g.instance.build.BUILD_ID}if(!(nd(t)&&!rd(t)))return g.instance.runtime[t]}});var na=require("node:async_hooks");var ra={request:new na.AsyncLocalStorage};var od="Error initializing gateway. Check your configuration for errors or contact support.",id="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Zn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(nt)??e.headers.get(ns)??crypto.randomUUID(),s=e.headers.get(rt),a={requestId:o,rayId:s};return ra.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await Ts(this.runtimeInit)}catch(c){this.handleError(c,id,e)}return Rs(i(async(c,l)=>{let d;try{d=await fe.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,od,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:g.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var pa=Qe(Be());function sd(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(sd,"lexer");function ko(n,e){e===void 0&&(e={});for(var t=sd(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(ud(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(R){if(c<t.length&&t[c].type===R)return t[c++].value},"tryConsume"),p=i(function(R){var M=d(R);if(M!==void 0)return M;var B=t[c],G=B.type,v=B.index;throw new TypeError("Unexpected ".concat(G," at ").concat(v,", expected ").concat(R))},"mustConsume"),f=i(function(){for(var R="",M;M=d("CHAR")||d("ESCAPED_CHAR");)R+=M;return R},"consumeText");c<t.length;){var h=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var O=h||"";o.indexOf(O)===-1&&(l+=O,O=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:O,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var H=h||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var O=f(),F=d("NAME")||"",Z=d("PATTERN")||"",j=f();p("CLOSE"),a.push({name:F||(Z?u++:""),pattern:F&&!Z?s:Z,prefix:O,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ko,"parse");function oa(n,e){return ad(ko(n,e),e)}i(oa,"compile");function ad(n,e){e===void 0&&(e={});var t=cd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var O=o(f[P],p);if(a&&!u[d].test(O))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var O=o(String(f),p);if(a&&!u[d].test(O))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix;continue}if(!h){var H=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}i(ad,"tokensToFunction");function ud(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(ud,"escapeString");function cd(n){return n&&n.sensitive?"":"i"}i(cd,"flags");var ua=Qe(Be());var ld=(0,ua.debug)("zuplo:runtime"),Mo=new TextEncoder,ia={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},dd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Et=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Do(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){ld("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=q.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Do=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:h,allHeaders:A,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let O,H;(!c||!l)&&([O,H]=pd(this.url,this.headers)),this.service=c||O||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(Z=>A||!dd.includes(Z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(Z=>Z+":"+(Z==="host"?this.url.host:(this.headers.get(Z)||"").replace(/\s+/g," "))).join(`
|
|
57
|
-
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!
|
|
53
|
+
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let _=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return _.length<=u.inlineCharacterLimit?_:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
54
|
+
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Ls(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((_,E)=>{let C=a.length-1===E?p.newline:","+p.newlineOrSpace,Z=s(_,u,c+d,l+1);return u.transform&&(Z=u.transform(a,E,Z)),p.indent+Z+C}).join("")+p.pad+"]";return r.pop(),h(y)}if(it(a)){let y=ks(a);if(u.filter&&(y=y.filter(E=>u.filter?.(a,E))),y.length===0)return"{}";r.push(a);let _="{"+p.newline+y.map((E,C)=>{let Z=y.length-1===C?p.newline:","+p.newlineOrSpace,N=typeof E=="symbol",j=!N&&/^[a-z$_][$\w]*$/i.test(E),q=N||j?E:s(E,u,"",l+1),B=s(a[E],u,c+d,l+1);return u.transform&&(B=u.transform(a,E,B)),p.indent+String(q)+": "+B+Z}).join("")+p.pad+"}";return r.pop(),h(_)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
55
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(vn,"stringifyObject");function Ke(n){return n.map(e=>Pe(e))}i(Ke,"makeErrorsSerializable");function Rt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:$e(Pe(e))}i(Rt,"extractBestMessage");function Ys(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Bt(t))if(t.stack)e.push(t.stack);else{let r=vn(Pe(t));e.push(r)}else if(typeof t=="object"){let r=vn(t);e.push(r)}else{let r=vo(t);e.push(r)}}),e.join(`
|
|
56
|
+
`)}i(Ys,"messagesToMultilineText");function $e(n){return typeof n=="string"?n:JSON.stringify(n)}i($e,"stringifyNonString");function vo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?po(n):"unknown"}i(vo,"stringifyNonStringToText");var Sn=require("jose");async function Ee(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(Ee,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Sn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function Xs(n,e,t){return Qs(n,{token:e,returnSecureToken:!0},t)}i(Xs,"exchangeFirebaseJwtForIdToken");async function On(n,e,t){return Qs(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(On,"exchangeGgpJwtForIdToken");async function Qs(n,e,t){let r=await Ee(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Qs,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,Sn.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Cn=class extends me{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Wt(this.options)}},Ql="https://logging.googleapis.com/v2/entries:write?alt=json",So={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Wt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=g.instance.loggingEnvironmentType,this.#i=g.instance.loggingEnvironmentStage,this.#r=g.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new Q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ke(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:So[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=Rt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(Ql,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new X("google-log-transport",1,this.dispatchFunction)};var An="gcp";function _n(n){let e={allMessages:Ke(n.messages)},t="zuplo-production",r=Rt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:So[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(_n,"gcpLogFormat");var Jt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_n(e)])}else this.#e.log(JSON.stringify(e))}};var Ln=class extends me{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Kt(this.options)}},Oo="__ddtags",Co="__ddattr",Ao=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ed=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ao(r)):t.push(`${Ao(r)}:${Ao(o.toString())}`)}),t.join(",")},"formatTags"),Kt=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Oo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Oo]!==void 0);a>-1&&(Object.assign(r,s[a][Oo]),s.splice(a,1));let u={},c=t.custom[Co];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Co]!==void 0);l>-1&&(Object.assign(u,s[l][Co]),s.splice(l,1));let d=Ke(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Rt(d),service:e.loggingId,ddtags:ed(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new X("data-dog-transport",10,this.dispatchFunction)};var Yt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_n(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var td=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ke(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),kn,Nn=class{static{i(this,"RemoteLogTransport")}constructor(e){kn||(kn=new X("remote-log-transport",1,td(e)))}log(e,t){kn.enqueue(e),t.waitUntil(kn.waitUntilFlushed())}};var nd={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ea=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:nd[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var rd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=ea(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Mn,Dn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Mn||(Mn=new X("unified-log-transport",1,rd(e)))}async log(e,t){Mn.enqueue(e),t.waitUntil(Mn.waitUntilFlushed())}};var _o=(0,ta.debug)("zuplo:logging"),Un=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(g.instance,e),r=await n.setupUserCoreLogger(g.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;_o("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Zt);return s?o.push(new Yt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Dn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Vt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){_o("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Zt);if(a&&a.captureUserLogs===!0?r.push(new Yt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Jt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Nn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Wt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return qe.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Vt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){_o("Gateway.createRequestLoggers");let a=new Tn(r,o,s),u=new Gt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Gt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ut=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Lo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Pt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},ko=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ut||e instanceof ue))throw new Q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Lo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new ko(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Pt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Pt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var No;function na(n){No=n}i(na,"setGlobalZuploEventContext");function Hn(){if(No===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return No}i(Hn,"getGlobalZuploEventContext");function ra({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);bs.includes(o.toLowerCase())&&!ws.includes(r.toLowerCase())&&t.delete(r)}t.delete(is)}else ys.forEach(r=>{t.delete(r)});return t}i(ra,"normalizeIncomingRequestHeaders");var Ue=(0,ia.debug)("zuplo:runtime"),od=i(n=>{let e=n.findIndex(t=>t.name===jt.name);return e>-1?[...n.splice(e),jt]:[...n,jt]},"setupSystemNoVersion"),he=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ue("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ue("Gateway.initialize"),!n.#e){let s=await Un.init(r),a=e(),u={...a,corsPolicies:Hs(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Q("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ue("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Q("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[xn,En,be];#o;setupRoutes=()=>{Ue("Gateway.setupRoutes");let e=this.routeData,t=od(e.versions),r=new Et(t);if(e.routes.length===0)return lo(r,this),bo(r,this),ho(r,this),Zs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ws(r,this),Gs(r,this)),lo(r,this),bo(r,this),ho(r,this);for(let s of qe)s instanceof Ze&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new ut(s);r.addRoute(c,u.execute)}),qs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ue("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ue("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Pe(r.cause);"stack"in s&&(s.stack=Ks(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;na(r);let a=ra({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(rt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Vr,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new Q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let _=new Zn(e.headers),E=new re(u,{params:y.params}),C=new qn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:_}),Z=y.routeConfiguration.raw();oa.trace.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:Z.operationId,[_e.RouteTrace]:Z["x-zuplo-trace"],[_e.RouteSystem]:gt(p)?!0:void 0});let N=ye.initialize(C,E);if(y.routeConfiguration===yo&&Ft.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(h);N.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof ut)}try{if(ne.addLogger(C,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(p):!p.pathname.startsWith("/__zuplo")){let P=await Ss(E,C);if(P instanceof Response)return P;{let D=ye.getContextExtensions(C);E=P,D.latestRequest=E}}gt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;id(j,y,u),Ue("Gateway.handleRequest - call user handler");let q=await j(E,C);if(Ue("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let B;if(q.headers.get(rt)===null&&!q.webSocket){let P=new Headers(q.headers);P.set(rt,o),B=new Response(q.body,{status:q.status,statusText:q.statusText,headers:P,cf:q.cf})}else B=q;return B}catch(j){return Ue("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(E,C,j)}}};function id(n,e,t){if(Ue("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(id,"checkHandler");var sa=i(async(n,e,t)=>{let r=he.instance.routeData.policies,o=zt([n],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Zn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Xr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Qr)??void 0}get city(){return this.#e.get(Gr)??this.#e.get(ds)??void 0}get continent(){return this.#e.get(Wr)??this.#e.get(ps)??void 0}get country(){return this.#e.get(Jr)??this.#e.get(ms)??void 0}get latitude(){return this.#e.get(Yr)??this.#e.get(fs)??void 0}get longitude(){return this.#e.get(Kr)??this.#e.get(gs)??void 0}get colo(){return this.#e.get(eo)??void 0}get postalCode(){return this.#e.get(cs)??this.#e.get(to)??void 0}get metroCode(){return this.#e.get(us)??this.#e.get(no)??void 0}get region(){return this.#e.get(ss)??this.#e.get(ro)??void 0}get regionCode(){return this.#e.get(as)??this.#e.get(oo)??void 0}get timezone(){return this.#e.get(ls)??this.#e.get(io)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},ft=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},qn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>sa(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var Ce=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var sd=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ad(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!sd.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(ad,"isRestrictedEnvVariableName");function ud(n){return!!n.startsWith("ZUPLO_")}i(ud,"isZuploReadableEnvVariableName");var Re=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return g.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return g.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return g.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return g.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return g.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return g.instance.build.BUILD_ID}if(!(ad(t)&&!ud(t)))return g.instance.runtime[t]}});var aa=require("node:async_hooks");var ua={request:new aa.AsyncLocalStorage};var cd="Error initializing gateway. Check your configuration for errors or contact support.",ld="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Fn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(rt)??e.headers.get(os)??crypto.randomUUID(),s=e.headers.get(ot),a={requestId:o,rayId:s};return ua.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await As(this.runtimeInit)}catch(c){this.handleError(c,ld,e)}return Es(i(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,cd,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:g.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var ya=et(ze());function dd(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(dd,"lexer");function Mo(n,e){e===void 0&&(e={});for(var t=dd(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(md(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(P){if(c<t.length&&t[c].type===P)return t[c++].value},"tryConsume"),p=i(function(P){var D=d(P);if(D!==void 0)return D;var z=t[c],W=z.type,S=z.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(P))},"mustConsume"),h=i(function(){for(var P="",D;D=d("CHAR")||d("ESCAPED_CHAR");)P+=D;return P},"consumeText");c<t.length;){var y=d("CHAR"),_=d("NAME"),E=d("PATTERN");if(_||E){var C=y||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:_||u++,prefix:C,suffix:"",pattern:E||s,modifier:d("MODIFIER")||""});continue}var Z=y||d("ESCAPED_CHAR");if(Z){l+=Z;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var C=h(),j=d("NAME")||"",q=d("PATTERN")||"",B=h();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:C,suffix:B,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Mo,"parse");function ca(n,e){return pd(Mo(n,e),e)}i(ca,"compile");function pd(n,e){e===void 0&&(e={});var t=gd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",_=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!_)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<h.length;E++){var C=o(h[E],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var Z=_?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(Z))}}return l}}i(pd,"tokensToFunction");function md(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(md,"escapeString");function gd(n){return n&&n.sensitive?"":"i"}i(gd,"flags");var ma=et(ze());var fd=(0,ma.debug)("zuplo:runtime"),Uo=new TextEncoder,la={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},hd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],It=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Ho(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){fd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Ho=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:_,singleEncode:E}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,Z;(!c||!l)&&([C,Z]=yd(this.url,this.headers)),this.service=c||C||"",this.region=l||Z||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let N=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>_||!hd.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
|
|
57
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");E||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=pa(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map(B=>pa(encodeURIComponent(B)))).sort(([q,B],[P,D])=>q<P?-1:q>P?1:B<D?-1:B>D?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Xt("AWS4"+this.secretAccessKey,e),s=await Xt(o,this.region),a=await Xt(s,this.service);r=await Xt(a,"aws4_request"),this.cache.set(t,r)}return Do(await Xt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Do(await da(await this.canonicalString()))].join(`
|
|
58
58
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
59
59
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
60
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new _("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=No(await sa(this.body||""))}return e}};async function Yt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mo.encode(e))}i(Yt,"hmac");async function sa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mo.encode(n):n)}i(sa,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function aa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(aa,"encodeRfc3986");function pd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ia?[ia[s],a]:[s,a]}i(pd,"guessServiceRegion");function md(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(md,"b64ToUint6");function ca(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=md(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ca,"base64Decode");function qn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(qn,"uint6ToB64");function la(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(qn(o>>>18&63),qn(o>>>12&63),qn(o>>>6&63),qn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(la,"base64Encode");function It(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(It,"numberToString");function gd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=It(Math.floor(t/60)),s=It(t%60);return`${r}${o}${s}`}i(gd,"getCLFOffset");function Uo(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=It(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=It(n.getHours()),a=It(n.getMinutes()),u=It(n.getSeconds()),c=gd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var da=(0,pa.debug)("zuplo:runtime"),fd="X-Amzn-Trace-Id",hd="x-amzn-errortype",ma=[],yd=i(async(n,e,t)=>{let r=t;for await(let o of ma)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Te=class extends _{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(fd)??void 0,this.errorType=t.get(hd)??void 0}},ga={addSendingAwsLambdaEventHook:n=>{ma.push(n)}};async function fa(n,e){let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new Et({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(da(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Pd(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,A;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?A=Rd(n,e):A=await wd(n,e,{useAwsResourcePathStyle:u}),da("Calling onSendingAwsLambdaEvent hook");let P=await yd(n,e,A);P.body=p,P.isBase64Encoded=f;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return bd(O)}catch(H){if(H instanceof Te){let k=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,k)}throw H}}i(fa,"awsLambdaHandler");async function bd(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);r=ca(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 Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(bd,"getResponse");async function wd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.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:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Id(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(wd,"buildEventVersion1");function Rd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Rd,"buildEventVersion2");async function Pd(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Ed(e,o)){let s=await n.arrayBuffer();t=la(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Pd,"getBodyResult");function Ed(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Ed,"matchesContentType");function Id(n,e=!1){if(!e)return n;let t=ko(n),r=oa(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Id,"getResourcePath");var xd=[502,503,504];async function xt(n,e){if(xd.includes(n.status)){let t=te.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(xt,"logBadGatewayResponses");var Ho;function Ke(n){if(Ho===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Ke,"getHandlerUserLogFunction");async function ha(n,e){let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Td(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await q.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,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 xt(l,e),l}i(ha,"openApiSpecHandler");var Td=i(n=>n.startsWith("./")?n.startsWith("./config")?n.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 ya(n,e){let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(ya,"redirectHandler");function vd(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(vd,"join");async function ba(n,e){let t=Ke(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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=vd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await q.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),xt(p,e),p}i(ba,"urlForwardHandler");var Sd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function wa(n,e){let t=Ke(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Sd(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await q.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),xt(d,e),d}i(wa,"urlRewriteHandler");async function Ra(n,e){let t=e.route.handler.options,r=Ke(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await q.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Ra,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Pa=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ea(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Pa(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Ea,"wireUpListeners");async function Ia(n,e){let t=e.route.handler.options,r=Ke(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await q.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let h=c.webSocket;h.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return Ea(p,h,n,e,A),Ea(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Ia,"webSocketPipelineHandler");var $n=class extends pe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new qo(this.options)}},qo=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(Re(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)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await q.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Y("dyna-trace-log-transport",10,this.#i)};var Fn=class extends pe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Fo(this.options)}},$o=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Od(n,e){return btoa(`${n}:${e}`)}i(Od,"createBasicDigest");var Fo=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Od(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new $o(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:$e(Re(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await q.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Y("loki-log-transport",10,this.#u)};var jn=class extends pe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(Re(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)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
61
|
-
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await
|
|
62
|
-
`),r=await
|
|
60
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Do(await da(this.body||""))}return e}};async function Xt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Uo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Uo.encode(e))}i(Xt,"hmac");async function da(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Uo.encode(n):n)}i(da,"hash");function Do(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Do,"buf2hex");function pa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(pa,"encodeRfc3986");function yd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in la?[la[s],a]:[s,a]}i(yd,"guessServiceRegion");function bd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(bd,"b64ToUint6");function ga(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=bd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ga,"base64Decode");function $n(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i($n,"uint6ToB64");function fa(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint($n(o>>>18&63),$n(o>>>12&63),$n(o>>>6&63),$n(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(fa,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function wd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(wd,"getCLFOffset");function Zo(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=wd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Zo,"toCLFDate");var ha=(0,ya.debug)("zuplo:runtime"),Rd="X-Amzn-Trace-Id",Pd="x-amzn-errortype",ba=[],Ed=i(async(n,e,t)=>{let r=t;for await(let o of ba)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ve=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Rd)??void 0,this.errorType=t.get(Pd)??void 0}},wa={addSendingAwsLambdaEventHook:n=>{ba.push(n)}};async function Ra(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ha(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await vd(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,_;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?_=Td(n,e):_=await xd(n,e,{useAwsResourcePathStyle:u}),ha("Calling onSendingAwsLambdaEvent hook");let E=await Ed(n,e,_);E.body=p,E.isBase64Encoded=h;let C=await l.fetch(d,{body:JSON.stringify(E)});try{return Id(C)}catch(Z){if(Z instanceof ve){let N=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&Z.traceId?{AMZN_TRACE_ID_HEADER:Z.traceId}:void 0;return T.internalServerError(n,e,void 0,N)}throw Z}}i(Ra,"awsLambdaHandler");async function Id(n){let e;try{e=await n.json()}catch{throw new ve("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);r=ga(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 ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Id,"getResponse");async function xd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.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:Zo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Od(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(xd,"buildEventVersion1");function Td(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Zo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Td,"buildEventVersion2");async function vd(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Sd(e,o)){let s=await n.arrayBuffer();t=fa(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(vd,"getBodyResult");function Sd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Sd,"matchesContentType");function Od(n,e=!1){if(!e)return n;let t=Mo(n),r=ca(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Od,"getResourcePath");var Cd=[502,503,504];async function Tt(n,e){if(Cd.includes(n.status)){let t=ne.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var qo;function Ye(n){if(qo===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),qo=t}return n.log[qo]}i(Ye,"getHandlerUserLogFunction");async function Pa(n,e){f("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ad(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Tt(l,e),l}i(Pa,"openApiSpecHandler");var Ad=i(n=>n.startsWith("./")?n.startsWith("./config")?n.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 Ea(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ea,"redirectHandler");function _d(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(_d,"join");async function Ia(n,e){f("handler.url-forward");let t=Ye(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 m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=_d(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),Tt(p,e),p}i(Ia,"urlForwardHandler");var Ld=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function xa(n,e){f("handler.url-rewrite");let t=Ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Ld(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(xa,"urlRewriteHandler");async function Ta(n,e){f("handler.websocket");let t=e.route.handler.options,r=Ye(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Ta,"webSocketHandler");var Fo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),va=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Sa(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await va(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Sa,"wireUpListeners");async function Oa(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=Ye(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),Z=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(Z)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let _=t.policies&&t.policies.inbound?Fo(t.policies.inbound,"inbound"):[],E=t.policies&&t.policies.outbound?Fo(t.policies.outbound,"outbound"):[];return Sa(p,y,n,e,_),Sa(y,p,n,e,E),new Response(null,{status:101,webSocket:d})}i(Oa,"webSocketPipelineHandler");var jn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new $o(this.options)}},$o=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(Pe(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)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new X("dyna-trace-log-transport",10,this.#i)};var Bn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Bo(this.options)}},jo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function kd(n,e){return btoa(`${n}:${e}`)}i(kd,"createBasicDigest");var Bo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=kd(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new jo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:$e(Pe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new X("loki-log-transport",10,this.#u)};var zn=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new zo(this.options)}},zo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(Pe(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)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
61
|
+
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new X("sumo-logic-log-transport",10,this.#s)};var Nd="d3a5b78f823648f5b1df4fe269d41172",Vn=class extends me{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Nd}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.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,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ys(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=vo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new X("vmware-log-insights-log-transport",10,this.#a)};var Gn=class extends me{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Go(this.options)}},Go=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new X("aws-log-transport",10,async e=>{if(e.length===0)return;let t=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:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){f("logging.aws"),this.awsClient=new It({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=g.instance.loggingEnvironmentType,this.environment=g.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:$e(Pe(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)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Wo=new WeakMap,Md={tags:[]},Wn=class extends Je{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Jo(this.options)}static setContext(t,r){let o=Wo.get(t);o||(o=Md);let s=Object.assign({...o},r);Wo.set(t,s)}},Jo=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new X("data-dog-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Wo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Ko(await r.text())}},Ko=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Yo=new WeakMap,Dd={dimensions:[]},Jn=class extends Je{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Xo(this.options)}static setContext(t,r){let o=Yo.get(t);o||(o=Dd);let s=Object.assign({...o},r);Yo.set(t,s)}},Xo=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new X("dynatrace-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Yo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
|
|
62
|
+
`),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Qo(await r.text())}},Qo=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Kn=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var Yn=class extends Ze{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new ei(e,this.#e,this.#t)}},Ca=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Ud={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ei=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Ud};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 X("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Ca(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Ca(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,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var ti=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},He=class extends ti{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Hd="v1",Zd=300;async function Aa(n,e,t,r=Zd,o){return await Fd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Aa,"constructEventAsync");function qd(n,e){return`${e.timestamp}.${n}`}i(qd,"makeHMACContent");async function Fd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=$d(n,e,Hd),l=/\s/.test(t),d=await Vd(qd(a,u),t);return jd(a,s,u,d,r,c,l,o)}i(Fd,"verifyHeaderAsync");function $d(n,e,t){if(!n)throw new He(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.decode(n):n;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 He(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Bd(a,t);if(!u||u.timestamp===-1)throw new He(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new He(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i($d,"parseEventDetails");function jd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(h=>zd(h,r)).length,l=`
|
|
63
63
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
64
64
|
|
|
65
|
-
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new
|
|
65
|
+
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new He(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
|
|
66
66
|
Signature verification is impossible without access to the original signed material.
|
|
67
67
|
`+l+`
|
|
68
|
-
`+d}):new
|
|
68
|
+
`+d}):new He(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
69
69
|
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.
|
|
70
70
|
`+l+`
|
|
71
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ue(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Hd,"validateComputedSignature");function Zd(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Zd,"parseHeader");function qd(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(qd,"secureCompare");async function $d(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ei[s[u]];return a.join("")}i($d,"computeHMACSignatureAsync");var ei=new Array(256);for(let n=0;n<ei.length;n++)ei[n]=n.toString(16).padStart(2,"0");function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var Tt=class extends be{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,t){oe(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 Ta(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function va(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}i(va,"isStripeWebhookEvent");var Fd={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new _(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new _(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new _(s)}return o}},Kn=Fd;var ti="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Sa="My API Key";async function Oa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,ti);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Sa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new _(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Oa,"createConsumer");async function Ca({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,ti);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Sa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new _(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ca,"createConsumerInvite");async function Aa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ti);o.searchParams.set("with-api-key","true");let s=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Aa,"deleteConsumer");async function _a({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=g.instance;if(!ht(p))throw new X("No Zuplo JWT token set.");let h=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,O="";try{P=await h.json(),O=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(A,P),new _(`${A} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}i(_a,"createSubscription");async function vt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!ht(o))throw new X("No Zuplo JWT token set.");let a=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new _(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(vt,"updateSubscription");async function St({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!ht(o))throw new X("No Zuplo JWT token set.");let a=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new _(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}return u.data[0]}i(St,"getSubscription");var ie="Skipping since we're unable to process the webhook event.",Ye="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Yn(n){return n.replaceAll("_","-")}i(Yn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function ni(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Oa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Kn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ca({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ie,detail:p.message})}if(!c)return x.ok(n,e,{title:ie,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Yn(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await _a({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:h})}catch(p){return await Aa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ie,detail:p.message})}return x.ok(n,e,{title:Ye})}i(ni,"onCustomerSubscriptionCreated");async function ri(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await vt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(n,e,{title:Ye})}i(ri,"onCustomerSubscriptionDeleted");async function oi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Yn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ye})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Kn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ye})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ye})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ie,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(oi,"onCustomerSubscriptionUpdated");var ii=class extends ln{constructor(t){super();this.options=t}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(we.ZUPLO_METERING_SERVICE_BUCKET_ID)d=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new X("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!jd(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!va(h))return x.ok(c,l,{title:ie,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await ni(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await oi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ri(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ie,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee})}},"stripeWebhookHandler"),s=Us({inboundPolicies:[new Tt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[ye,s],handler:o,gateway:r}),u=new ae({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function jd(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(jd,"isMetricsRegion");var ka=new WeakMap,La={},Xn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ka.set(e,t)}};async function Na(n,e,t,r){if(!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=yt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ka.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=it(n.user,t.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??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.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(t.dimensions??{},a?.dimensions)},f=La[t.apiKey];if(!f){let h=t.apiKey,A=n.headers.get("zm-test-id")??"";f=new Y("amberflo-ingest-meter",10,async P=>{try{let O=t.url??"https://app.amberflo.io/ingest",H=await q.fetch(O,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":A}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),La[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Na,"AmberfloMeteringInboundPolicy");async function Qn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(Qn,"sha256");var Ma=new Map;async function me(n,e,t){let r,o=`${n}-${e}`,s=Ma.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await Qn(JSON.stringify({policyName:n,options:t}))}`,Ma.set(n,r)),r}i(me,"getPolicyCacheName");var Da="key-metadata-cache-type";function Bd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Bd,"getKeyValue");async function er(n,e,t,r){if(!t.bucketName)if(we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(O=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:O}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Bd(a,o);if(!u||u==="")return s("No key present");let c=await zd(u),l=await me(r,void 0,o),d=new le(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Da&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},h=await Pe({retryDelayMs:5,retries:2,logger:te.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let O=await h.text(),H=JSON.parse(O);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let A=await h.json(),P={isValid:!0,typeId:Da,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(er,"ApiKeyInboundPolicy");async function zd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(zd,"hashValue");var Ua=er;var Xt=require("jose");var Ha=require("jose");var si=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof ai&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,Ha.createLocalJWKSet)(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await q.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new ui("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Ot("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Ot("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Za(n,e,t){let r=new si(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Za,"createRemoteJWKSet");var Ot=class extends _{static{i(this,"JWKSError")}},ai=class extends Ot{static{i(this,"JWKSNoMatchingKey")}},ui=class extends Ot{static{i(this,"JWKSTimeout")}};var tr={},Vd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!tr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await me(n,void 0,r),u=new le(a,e);tr[r.jwkUrl]=Za(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else tr[r.jwkUrl]=(0,Xt.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,Xt.jwtVerify)(t,tr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Gd=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,Xt.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ge=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),s="bearer ",a=i(f=>x.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Vd(r,e):Gd,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=o.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(h){let A=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var qa=i(async(n,e,t,r)=>ge(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var nr=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await q.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Wd=[],rr=class n extends be{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new nr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:x.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of Wd)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Ls(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new _(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var $a=i(async(n,e,t)=>{let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),A=t.accounts.find(P=>P.username===f&&P.password===h);return A||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function or(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(or,"extractDateElements");function Fa(n,e){return new Date(n,e+1,0).getDate()}i(Fa,"getDaysInMonth");function ci(n,e){return n<=e?e-n:6-n+e+1}i(ci,"getDaysBetweenWeekdays");var ir=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=Fa(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?ci(d,p):ci(p,d);l=e==="next"?o+f:o-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=or(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=or(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=or(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Jd={min:0,max:59},Kd={min:0,max:59},Yd={min:0,max:23},Xd={min:1,max:31},Qd={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ep={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},tp={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ct(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{ct(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ct,"parseElement");function li(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=tp[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new ir({seconds:ct(t,Jd),minutes:ct(r,Kd),hours:ct(o,Yd),days:ct(s,Xd),months:new Set(Array.from(ct(a,Qd)).map(c=>c-1)),weekdays:new Set(Array.from(ct(u,ep)).map(c=>c%7))})}i(li,"parseCronExpression");var sr=class extends be{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),oe(e,t).optional("problem","object"),e.problem&&oe(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[li(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>li(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var np=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function rp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(rp,"digestMessage");var op=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await rp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function ja(n,e,t,r){let o=await me(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await op(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,h=new Response(p.body,p);np.forEach(A=>h.headers.delete(A)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(ja,"CachingInboundPolicy");var Ba=i(async(n,e,t,r)=>{if(!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ne(n,{method:t.method})},"ChangeMethodInboundPolicy");var za=i(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ne(n,{headers:o})},"ClearHeadersInboundPolicy");var Va=i(async(n,e,t,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Ga=i(async(n,e,t,r)=>{let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ge(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Wa=i(async(n,e,t,r)=>{if(!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return ge(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ja=i(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=fe.instance,s=Bt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var Ka=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=ip(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await me(r,void 0,t),u=new le(a,e),c=await u.get(s);if(!c){let l=await q.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function ip(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(ip,"getToken");var Ya=i(async(n,e,t,r)=>(oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ge(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Xa=i(async(n,e,t)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ne(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ct="__unknown__",Qa=i(async(n,e,t,r)=>{let o={allow:{countries:_t(t.allow?.countries,"allow.countries",r),regionCodes:_t(t.allow?.regionCodes,"allow.regionCode",r),asns:_t(t.allow?.asns,"allow.asOrganization",r)},block:{countries:_t(t.block?.countries,"block.countries",r),regionCodes:_t(t.block?.regionCodes,"block.regionCode",r),asns:_t(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Ct,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ct,u=e.incomingRequestProperties.asn?.toString()??Ct,c=o.ignoreUnknown&&s===Ct,l=o.ignoreUnknown&&a===Ct,d=o.ignoreUnknown&&u===Ct,p=o.allow.countries,f=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return At(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,O=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?At(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function At(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(At,"blockedResponse");function _t(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(_t,"toLowerStringArray");var eu=i(async(n,e,t)=>{let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var nu=i(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return di(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return di(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return tu(a[u])}else return a.length>0?tu(a[0]):di(r,n,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 tu(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(tu,"generateResponse");var di=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var sp="Incoming",ap={logRequestBody:!0,logResponseBody:!0};function ru(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(ru,"headersToObject");function ou(){return new Date().toISOString()}i(ou,"timestamp");var pi=new WeakMap,up={};function au(n,e){let t=pi.get(n);t||(t=up);let r=Object.assign({...t},e);pi.set(n,r)}i(au,"setMoesifContext");async function iu(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(iu,"readBody");var cp={},mi;function su(){if(!mi)throw new _("Invalid State - no _lastLogger");return mi}i(su,"getLastLogger");function lp(n){let e=cp[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);su().debug("posting",r);let o=await q.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||su().error({status:o.status,body:await o.text()})})),e}i(lp,"getDispatcher");async function uu(n,e,t,r){mi=e.log;let o=ou(),s=Object.assign(ap,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await iu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=lp(s.applicationId),d=n.headers.get("true-client-ip"),p=pi.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ru(n.headers)},h=s.logResponseBody?await iu(u,e):void 0,A={time:ou(),status:u.status,headers:ru(u.headers),body:h},P={request:f,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:sp};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(uu,"MoesifInboundPolicy");async function cu(n,e,t,r){let o=te.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await q.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(cu,"loadSubscription");async function lu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=te.getLogger(n);try{let c=await q.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(lu,"consumeSubcriptionQuotas");var dp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ar(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(ar,"validateMeters");function du(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=st(n),r=[];for(let o of t)dp.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(du,"parseAllowedSubscriptionStatuses");function pu(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(pu,"compareMeters");var ur=class extends be{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return Oe.get(e,Ut)}static setMeters(e,t){ar(t,"setMeters"),Oe.set(e,cn,t)}async handler(e,t){oe(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=yt(this.options.meterOnStatusCodes),s=Oe.get(t,cn),a={...this.options.meters,...s};ar(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=du(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,O,H)=>{let k=Oe.get(H,Ut);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(we.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=Oe.get(H,cn),j={...this.options.meters,...Z};if(ar(j,this.policyName),o.includes(P.status)&&k&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:R,metersNotInSubscription:M}=pu(k.meters,j);if(M&&Object.keys(M).length>0){let B=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${B}'`)}await lu(H,k.id,this.policyName,this.options.bucketId,R)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(we.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await cu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),Oe.set(t,Ut,p));let f=Oe.get(t,Ut);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var mu=i(async(n,e,t,r)=>ge(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var gu=require("jose");var gi,fu=i(async(n,e,t,r)=>{if(!gi)try{gi=await(0,gu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ge(n,e,{issuer:t.authUrl,secret:gi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ru=Qe(Be());var yu=Qe(Be());var cr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},fi=class extends cr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},hi=class extends cr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function pp(n,e){if(As(n))throw new fi(e)}i(pp,"throwIfUndefinedOrNull");function Qt(n,e){if(pp(n,e),!Ie(n))throw new hi(e,"string")}i(Qt,"throwIfNotString");var lr=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return Qt(e,"redisClientUrl"),Qt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){Qt(e,"url");let s=await q.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new X("Rate limiting service failed with 401: Unauthorized"):new X(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},dr=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Qt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new X("The in-memory redis client only supports /rate-limit calls")}};var mp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),mr=i(async n=>({key:`ip-${mp(n)}`}),"getIP"),gr=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),fr=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pr;function hr(n,e){let t;if(pr)return pr;if(g.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new dr,pr=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Ie(o))throw new X(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new X(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=lr.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new X(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return pr=t,t}i(hr,"getRedisClient");async function yr(n,e,t,r,o){let s=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:n}),requestId:o})}i(yr,"getCountAndUpdateExpiry");function br(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await t(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new _(c)}return u},"outerFunction")}i(br,"wrapUserFunction");var wr="Retry-After";var hu=(0,yu.debug)("zuplo:policies:RateLimitInboundPolicy"),bu=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((R,M)=>{let B={};return(!R||R==="retry-after")&&(B[wr]=M.toString()),x.tooManyRequests(n,e,void 0,B)},"rateLimited"),u={function:br(t,r),user:gr,ip:mr,all:fr}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,f=t.headerMode??"retry-after",h=hr(r,o),P=`bucket/${g.instance.build.BUILD_ID}/${r}/${l}`,O=await me(r,void 0,t),H=new le(O,e),k=yr(P,p,h,o,e.requestId),F;i(async()=>{let R=await k;if(R.count>d){let M=Date.now()+R.ttlSeconds*1e3;H.put(P,M,R.ttlSeconds),hu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${P}' (async mode)`),F=s(f,R.ttlSeconds)}},"asyncCheck")();let j=await H.get(P);if(j!==void 0&&j>Date.now()){hu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${P}' (async mode)`);let R=Math.round((j-Date.now())/1e3);return s(f,R)}return e.addResponseSendingHook(async R=>F??R),n},"AsyncRateLimitInboundPolicy");var wu=(0,Ru.debug)("zuplo:policies:RateLimitInboundPolicy"),gp="strict",yi=i(async(n,e,t,r)=>{if((t.mode??gp)==="async")return bu(n,e,t,r);let s=Date.now(),a=te.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new X(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[wr]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:br(t,r),user:gr,ip:mr,all:fr}[t.rateLimitBy],p=await d(n,e,r),f=p.key,h=p.requestsAllowed??t.requestsAllowed,A=p.timeWindowMinutes??t.timeWindowMinutes,P=t.headerMode??"retry-after",O=hr(r,a),k=`bucket/${g.instance.build.BUILD_ID}/${r}/${f}`,F=await yr(k,A,O,a,e.requestId);return F.count>h?(wu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (strict mode)`),c(P,F.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;wu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var bi;function Pu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Pu,"headersToNameValuePairs");function fp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(fp,"queryToNameValueParis");function hp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(hp,"parseIntOrUndefined");var Eu={};async function Iu(n,e,t,r){let o=new Date,s=Date.now();return bi||(bi={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?it(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?it(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:bi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Pu(n.headers),queryString:fp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Pu(a.headers),content:{size:hp(n.headers.get("content-length"))}}}]}}},d=Eu[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async f=>{try{let h=t.url??"https://metrics.readme.io/request",A=await q.fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Eu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Iu,"ReadmeMetricsInboundPolicy");var xu=i(async(n,e,t,r)=>{let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new ne(n,{headers:s})},"RemoveHeadersInboundPolicy");var Tu=i(async(n,e,t,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var vu=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new ne(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Su=i(async(n,e,t,r)=>{let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ou=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Cu=i(async(n,e,t)=>{let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Ou():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ou():n},"RequestSizeLimitInboundPolicy");function Au(n,e,t){return`_${Xe(n+"_"+e+"_"+t)}`}i(Au,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${Xe(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${Xe(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Xe(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function _u(n,e){return`_${Xe(n)}__${Xe(e)}`}i(_u,"getIdForRefSchema");function Xe(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);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(n.charAt(t)):e.push("_")}return e.join("")}i(Xe,"sanitizedIdentifierName");var Lt=i(n=>{let e=n.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"),kt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Rr(t,r,o,c.name),p=fe.instance.schemaValidator[d],f=p(e[c.name]),h=wi(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),_e=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Le=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),ke=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),wi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Lu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${h}`});if(Le(t.validateBody)&&_e(n,t.logLevel??"info",A,[r],h),ke(t.validateBody))return P}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=x.badRequest(e,n,{detail:h});return Le(t.validateBody)&&_e(n,t.logLevel??"info",h,[r],[h]),ke(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Pr(n.route.path,e.method,o),u=fe.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=x.badRequest(e,n,{detail:h});return Le(t.validateBody)&&_e(n,t.logLevel??"info",h,[r],[h]),ke(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=wi(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Le(t.validateBody)&&_e(n,t.logLevel??"info",d,[r],p),ke(t.validateBody))return f}i(Lu,"handleBodyValidation");function ku(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Lt(n),s=kt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(Le(t.validateHeaders)&&_e(n,t.logLevel??"info",a,s.invalidValues,s.errors),ke(t.validateHeaders))return u}}i(ku,"handleHeadersValidation");function Nu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Lt(n),o=kt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Le(t.validatePathParameters)&&_e(n,t.logLevel??"info",s,o.invalidValues,o.errors),ke(t.validatePathParameters))return a}}i(Nu,"handlePathParameterValidation");function Mu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Lt(n),o=kt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Le(t.validateQueryParameters)&&_e(n,t.logLevel??"info",s,o.invalidValues,o.errors),ke(t.validateQueryParameters))return a}}i(Mu,"handleQueryParameterValidation");var Ri=i(async(n,e,t)=>{let r=Mu(e,n,t);if(r!==void 0||(r=Nu(e,n,t),r!==void 0)||(r=ku(e,n,t),r!==void 0))return r;let o=await Lu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Du=Ri;var Uu=i(async(n,e,t,r)=>{if(t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Hu=i(async(n,e,t)=>new ne(n,{body:t.body}),"SetBodyInboundPolicy");var Zu=i(async(n,e,t,r)=>{let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new ne(n,{headers:s})},"SetHeadersInboundPolicy");var qu=i(async(n,e,t,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var $u=i(async(n,e,t,r)=>{let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new ne(s.toString(),n)},"SetQueryParamsInboundPolicy");var Fu=i(async(n,e,t,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(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var yp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),ju=i(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await yp(t.sleepInMs),n},"SleepInboundPolicy");var Bu=i(async(n,e,t,r)=>{oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ge(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof ne))throw new X("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new _(`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?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var zu=i(async(n,e,t,r)=>{oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await me(r,void 0,t),s=new le(o,e),a=await s.get(r);if(!a){let u=await bp(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function bp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Pe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new _("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 _("Response returned from Azure AD is not in the expected format.")}i(bp,"getAccessToken");var Vu="https://accounts.google.com/o/oauth2/token",Pi,Gu=i(async(n,e,t,r)=>{oe(t,r).required("serviceAccountJson","string"),Pi||(Pi=await xe.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await me(r,void 0,t),a=new le(s,e),u=await a.get(r);if(!u){let c=await Me({serviceAccount:Pi,audience:Vu,payload:o}),l=await vn(Vu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var wp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Rp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ei,Wu=i(async(n,e,t,r)=>{if(oe(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Rp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ei||(Ei=await xe.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new _("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=it(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new _(`Unable to determine user from for the policy ${r}`);let a=await me(r,void 0,t),u=new le(a,e),c={uid:s,claims:o},l=await Qn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Me({serviceAccount:Ei,audience:wp,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Gs(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new _("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ii,Ju=i(async(n,e,t,r)=>{oe(t,r).required("audience","string").required("serviceAccountJson","string"),Ii||(Ii=await xe.init(t.serviceAccountJson));let o=await Me({serviceAccount:Ii,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ku="https://www.googleapis.com/oauth2/v4/token",xi,Yu=i(async(n,e,t,r)=>{oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),xi||(xi=await xe.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=st(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await me(r,void 0,t),a;t.useMemoryCacheOnly?a=new lt(s):a=new le(s,e);let u=await a.get(r);if(!u){let c=await Me({serviceAccount:xi,audience:Ku,payload:o}),l=await vn(Ku,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Xu=i(async(n,e,t)=>{let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new X("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Qu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,O)=>e(P,"name",{value:O,configurable:!0}),"__name"),o=i((P,O)=>i(function(){return O||(0,P[t(P)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,F){return F},attributeValueProcessor:function(k,F){return F},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,F,Z){return k}},H=r(function(k){return Object.assign({},O,k)},"buildOptions");P.buildOptions=H,P.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var O=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",H=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+H+"]*",F=new RegExp("^"+k+"$"),Z=r(function(R,M){let B=[],G=M.exec(R);for(;G;){let v=[];v.startIndex=M.lastIndex-G[0].length;let I=G.length;for(let U=0;U<I;U++)v.push(G[U]);B.push(v),G=M.exec(R)}return B},"getAllMatches"),j=r(function(R){let M=F.exec(R);return!(M===null||typeof M>"u")},"isName");P.isExist=function(R){return typeof R<"u"},P.isEmptyObject=function(R){return Object.keys(R).length===0},P.merge=function(R,M,B){if(M){let G=Object.keys(M),v=G.length;for(let I=0;I<v;I++)B==="strict"?R[G[I]]=[M[G[I]]]:R[G[I]]=M[G[I]]}},P.getValue=function(R){return P.isExist(R)?R:""},P.isName=j,P.getAllMatches=Z,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,O){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,F){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:F})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};O.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,O){var H=a();function k(v,I){let U={};if(v[I+3]==="O"&&v[I+4]==="C"&&v[I+5]==="T"&&v[I+6]==="Y"&&v[I+7]==="P"&&v[I+8]==="E"){I=I+9;let ue=1,K=!1,Q=!1,ve="";for(;I<v.length;I++)if(v[I]==="<"&&!Q){if(K&&j(v,I))I+=7,[entityName,val,I]=F(v,I+1),val.indexOf("&")===-1&&(U[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&R(v,I))I+=8;else if(K&&M(v,I))I+=8;else if(K&&B(v,I))I+=9;else if(Z)Q=!0;else throw new Error("Invalid DOCTYPE");ue++,ve=""}else if(v[I]===">"){if(Q?v[I-1]==="-"&&v[I-2]==="-"&&(Q=!1,ue--):ue--,ue===0)break}else v[I]==="["?K=!0:ve+=v[I];if(ue!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:I}}i(k,"readDocType"),r(k,"readDocType");function F(v,I){let U="";for(;I<v.length&&v[I]!=="'"&&v[I]!=='"';I++)U+=v[I];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ue=v[I++],K="";for(;I<v.length&&v[I]!==ue;I++)K+=v[I];return[U,K,I]}i(F,"readEntityExp"),r(F,"readEntityExp");function Z(v,I){return v[I+1]==="!"&&v[I+2]==="-"&&v[I+3]==="-"}i(Z,"isComment"),r(Z,"isComment");function j(v,I){return v[I+1]==="!"&&v[I+2]==="E"&&v[I+3]==="N"&&v[I+4]==="T"&&v[I+5]==="I"&&v[I+6]==="T"&&v[I+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function R(v,I){return v[I+1]==="!"&&v[I+2]==="E"&&v[I+3]==="L"&&v[I+4]==="E"&&v[I+5]==="M"&&v[I+6]==="E"&&v[I+7]==="N"&&v[I+8]==="T"}i(R,"isElement"),r(R,"isElement");function M(v,I){return v[I+1]==="!"&&v[I+2]==="A"&&v[I+3]==="T"&&v[I+4]==="T"&&v[I+5]==="L"&&v[I+6]==="I"&&v[I+7]==="S"&&v[I+8]==="T"}i(M,"isAttlist"),r(M,"isAttlist");function B(v,I){return v[I+1]==="!"&&v[I+2]==="N"&&v[I+3]==="O"&&v[I+4]==="T"&&v[I+5]==="A"&&v[I+6]==="T"&&v[I+7]==="I"&&v[I+8]==="O"&&v[I+9]==="N"}i(B,"isNotation"),r(B,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(G,"validateEntityName"),r(G,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,O){var H=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(R,M={}){if(M=Object.assign({},F,M),!R||typeof R!="string")return R;let B=R.trim();if(M.skipLike!==void 0&&M.skipLike.test(B))return R;if(M.hex&&H.test(B))return Number.parseInt(B,16);{let G=k.exec(B);if(G){let v=G[1],I=G[2],U=j(G[3]),ue=G[4]||G[6];if(!M.leadingZeros&&I.length>0&&v&&B[2]!==".")return R;if(!M.leadingZeros&&I.length>0&&!v&&B[1]!==".")return R;{let K=Number(B),Q=""+K;return Q.search(/[eE]/)!==-1||ue?M.eNotation?K:R:B.indexOf(".")!==-1?Q==="0"&&U===""||Q===U||v&&Q==="-"+U?K:R:I?U===Q||v+U===Q?K:R:B===Q||B===v+Q?K:R}}else return R}}i(Z,"toNumber"),r(Z,"toNumber");function j(R){return R&&R.indexOf(".")!==-1&&(R=R.replace(/0+$/,""),R==="."?R="0":R[0]==="."?R="0"+R:R[R.length-1]==="."&&(R=R.substr(0,R.length-1))),R}i(j,"trimZeros"),r(j,"trimZeros"),O.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,O){"use strict";var H=a(),k=u(),F=c(),Z=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(w){this.options=w,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(E,C)=>String.fromCharCode(Number.parseInt(C,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,C)=>String.fromCharCode(Number.parseInt(C,16))}},this.addExternalEntities=R,this.parseXml=I,this.parseTextData=M,this.resolveNameSpace=B,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ue,this.readStopNodeData=V,this.saveTextToParentTag=K,this.addChild=U}};function R(w){let E=Object.keys(w);for(let C=0;C<E.length;C++){let z=E[C];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:w[z]}}}i(R,"addExternalEntities"),r(R,"addExternalEntities");function M(w,E,C,z,L,N,ee){if(w!==void 0&&(this.options.trimValues&&!z&&(w=w.trim()),w.length>0)){ee||(w=this.replaceEntitiesValue(w));let $=this.options.tagValueProcessor(E,w,C,L,N);return $==null?w:typeof $!=typeof w||$!==w?$:this.options.trimValues?ce(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?ce(w,this.options.parseTagValue,this.options.numberParseOptions):w}}i(M,"parseTextData"),r(M,"parseTextData");function B(w){if(this.options.removeNSPrefix){let E=w.split(":"),C=w.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(w=C+E[1])}return w}i(B,"resolveNameSpace"),r(B,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(w,E,C){if(!this.options.ignoreAttributes&&typeof w=="string"){let z=H.getAllMatches(w,G),L=z.length,N={};for(let ee=0;ee<L;ee++){let $=this.resolveNameSpace(z[ee][1]),D=z[ee][4],se=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(se=this.options.transformAttributeName(se)),se==="__proto__"&&(se="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let re=this.options.attributeValueProcessor($,D,E);re==null?N[se]=D:typeof re!=typeof D||re!==D?N[se]=re:N[se]=ce(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[se]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var I=r(function(w){w=w.replace(/\r\n?/g,`
|
|
72
|
-
`);let
|
|
73
|
-
`&&
|
|
74
|
-
`||
|
|
71
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(jd,"validateComputedSignature");function Bd(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Bd,"parseHeader");function zd(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(zd,"secureCompare");async function Vd(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ni[s[u]];return a.join("")}i(Vd,"computeHMACSignatureAsync");var ni=new Array(256);for(let n=0;n<ni.length;n++)ni[n]=n.toString(16).padStart(2,"0");function ie(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(ie,"optionValidator");var vt=class extends we{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){ie(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 Aa(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function _a(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(_a,"isStripeWebhookEvent");var Gd={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o}},Xn=Gd;var ri="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",La="My API Key";async function ka({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,ri);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:La,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ka,"createConsumer");async function Na({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,ri);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:La,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new L(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Na,"createConsumerInvite");async function Ma({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ri);o.searchParams.set("with-api-key","true");let s=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ma,"deleteConsumer");async function Da({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=g.instance;if(!yt(p))throw new Q("No Zuplo JWT token set.");let y=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let _=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,E,C="";try{E=await y.json(),C=E.detail??E.title}catch{E={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(_,E),new L(`${_} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Da,"createSubscription");async function St({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Q("No Zuplo JWT token set.");let a=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(St,"updateSubscription");async function Ot({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Q("No Zuplo JWT token set.");let a=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(Ot,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Qn(n){return n.replaceAll("_","-")}i(Qn,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function oi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:se,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:se,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ka({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Xn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Na({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:se,detail:p.message})}if(!c)return T.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Qn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Da({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await Ma({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:se,detail:p.message})}return T.ok(n,e,{title:Xe})}i(oi,"onCustomerSubscriptionCreated");async function ii(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:se,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await St({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:se,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return T.ok(n,e,{title:Xe})}i(ii,"onCustomerSubscriptionDeleted");async function si(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==g.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:se,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Qn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:se,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return T.ok(n,e,{title:Xe})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Xn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:se,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return T.ok(n,e,{title:Xe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:se,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return T.ok(n,e,{title:Xe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:se,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}i(si,"onCustomerSubscriptionUpdated");var ai=class extends dn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("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 m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new Q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!Wd(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!_a(y))return T.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await oi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await si(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ii(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:se,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),s=$s({inboundPolicies:[new vt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});ie(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[be,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Wd(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Wd,"isMetricsRegion");var Ha=new WeakMap,Ua={},er=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ha.set(e,t)}};async function Za(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ha.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=st(n.user,t.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??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.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(t.dimensions??{},a?.dimensions)},h=Ua[t.apiKey];if(!h){let y=t.apiKey,_=n.headers.get("zm-test-id")??"";h=new X("amberflo-ingest-meter",10,async E=>{try{let C=t.url??"https://app.amberflo.io/ingest",Z=await F.fetch(C,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":_}});Z.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${Z.status}: ${await Z.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),Ua[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Za,"AmberfloMeteringInboundPolicy");async function tr(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(tr,"sha256");var qa=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=qa.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await tr(JSON.stringify({policyName:n,options:t}))}`,qa.set(n,r)),r}i(ge,"getPolicyCacheName");var Fa="key-metadata-cache-type";function Jd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Jd,"getKeyValue");async function nr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(C=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Jd(a,o);if(!u||u==="")return s("No key present");let c=await Kd(u),l=await ge(r,void 0,o),d=new de(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Fa&&ne.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),Z=JSON.parse(C);e.log.error("Unexpected response from key service",Z)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let _=await y.json(),E={isValid:!0,typeId:Fa,user:{sub:_.name,data:_.metadata}};return n.user=E.user,d.put(c,E,o.cacheTtlSeconds),n}i(nr,"ApiKeyInboundPolicy");async function Kd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Kd,"hashValue");var $a=nr;var Qt=require("jose");var ja=require("jose");var ui=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof ci&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,ja.createLocalJWKSet)(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new li("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Ct("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Ct("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ba(n,e,t){let r=new ui(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ba,"createRemoteJWKSet");var Ct=class extends L{static{i(this,"JWKSError")}},ci=class extends Ct{static{i(this,"JWKSNoMatchingKey")}},li=class extends Ct{static{i(this,"JWKSTimeout")}};var rr={},Yd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!rr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);rr[r.jwkUrl]=Ba(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else rr[r.jwkUrl]=(0,Qt.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,Qt.jwtVerify)(t,rr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Xd=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,Qt.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),fe=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Yd(r,e):Xd,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let _=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${_.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${_.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var za=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),fe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var or=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Qd=[],ir=class n extends we{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),ie(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new or(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:T.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of Qd)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Us(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new L(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Va=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),_=t.accounts.find(E=>E.username===h&&E.password===y);return _||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function sr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(sr,"extractDateElements");function Ga(n,e){return new Date(n,e+1,0).getDate()}i(Ga,"getDaysInMonth");function di(n,e){return n<=e?e-n:6-n+e+1}i(di,"getDaysBetweenWeekdays");var ar=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=Ga(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?di(d,p):di(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=sr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=sr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=sr(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var ep={min:0,max:59},tp={min:0,max:59},np={min:0,max:23},rp={min:1,max:31},op={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},ip={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},sp={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function pi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=sp[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new ar({seconds:lt(t,ep),minutes:lt(r,tp),hours:lt(o,np),days:lt(s,rp),months:new Set(Array.from(lt(a,op)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,ip)).map(c=>c%7))})}i(pi,"parseCronExpression");var ur=class extends we{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),ie(e,t).optional("problem","object"),e.problem&&ie(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[pi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>pi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(s,e,t)}return e}};var ap=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function up(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(up,"digestMessage");var cp=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await up(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Wa(n,e,t,r){f("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await cp(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);ap.forEach(_=>y.headers.delete(_)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Wa,"CachingInboundPolicy");var Ja=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ka=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var Ya=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Xa=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",fe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Qa=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return fe(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var eu=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,s=zt(t.policies,o?.routeData.policies);return Io(s)(n,e)},"CompositeInboundPolicy");var tu=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=lp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(a,e),c=await u.get(s);if(!c){let l=await F.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function lp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(lp,"getToken");var nu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),ie(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),fe(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ru=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var At="__unknown__",ou=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Lt(t.allow?.countries,"allow.countries",r),regionCodes:Lt(t.allow?.regionCodes,"allow.regionCode",r),asns:Lt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Lt(t.block?.countries,"block.countries",r),regionCodes:Lt(t.block?.regionCodes,"block.regionCode",r),asns:Lt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??At,a=e.incomingRequestProperties.regionCode?.toLowerCase()??At,u=e.incomingRequestProperties.asn?.toString()??At,c=o.ignoreUnknown&&s===At,l=o.ignoreUnknown&&a===At,d=o.ignoreUnknown&&u===At,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return _t(n,e,r,s,a,u);let _=o.block.countries,E=o.block.regionCodes,C=o.block.asns;return _.length>0&&_.includes(s)&&!c||E.length>0&&E.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?_t(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function _t(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(_t,"blockedResponse");function Lt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(Lt,"toLowerStringArray");var iu=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var au=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return mi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return mi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return su(a[u])}else return a.length>0?su(a[0]):mi(r,n,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 su(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(su,"generateResponse");var mi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var dp="Incoming",pp={logRequestBody:!0,logResponseBody:!0};function uu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(uu,"headersToObject");function cu(){return new Date().toISOString()}i(cu,"timestamp");var gi=new WeakMap,mp={};function pu(n,e){let t=gi.get(n);t||(t=mp);let r=Object.assign({...t},e);gi.set(n,r)}i(pu,"setMoesifContext");async function lu(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(lu,"readBody");var gp={},fi;function du(){if(!fi)throw new L("Invalid State - no _lastLogger");return fi}i(du,"getLastLogger");function fp(n){let e=gp[n];return e||(e=new X("moesif-inbound",100,async t=>{let r=JSON.stringify(t);du().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||du().error({status:o.status,body:await o.text()})})),e}i(fp,"getDispatcher");async function mu(n,e,t,r){f("policy.inbound.moesif-analytics"),fi=e.log;let o=cu(),s=Object.assign(pp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await lu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=fp(s.applicationId),d=n.headers.get("true-client-ip"),p=gi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:uu(n.headers)},y=s.logResponseBody?await lu(u,e):void 0,_={time:cu(),status:u.status,headers:uu(u.headers),body:y},E={request:h,response:_,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:dp};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),n}i(mu,"MoesifInboundPolicy");async function gu(n,e,t,r){let o=ne.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(gu,"loadSubscription");async function fu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ne.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(fu,"consumeSubcriptionQuotas");var hp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function cr(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(cr,"validateMeters");function hu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)hp.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(hu,"parseAllowedSubscriptionStatuses");function yu(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(yu,"compareMeters");var lr=class extends we{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return Ce.get(e,Ht)}static setMeters(e,t){cr(t,"setMeters"),Ce.set(e,ln,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){ie(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=bt(this.options.meterOnStatusCodes),s=Ce.get(t,ln),a={...this.options.meters,...s};cr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=hu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(E,C,Z)=>{let N=Ce.get(Z,Ht);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){Z.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 m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=Ce.get(Z,ln),B={...this.options.meters,...q};if(cr(B,this.policyName),o.includes(E.status)&&N&&B){Z.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(B)} on response status '${E.status}'`);let{metersInSubscription:P,metersNotInSubscription:D}=yu(N.meters,B);if(D&&Object.keys(D).length>0){let z=Object.keys(D);Z.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${z}'`)}await fu(Z,N.id,this.policyName,this.options.bucketId,P)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{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 m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await gu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),Ce.set(t,Ht,p));let h=Ce.get(t,Ht);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let _=Object.keys(a).filter(E=>!Object.keys(h.meters).includes(E));if(_.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${_.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${_.join(", ")}`,title:"Quota Exceeded"});for(let E of Object.keys(a))if(h.meters[E].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${E}'`,title:"Quota Exceeded"});return e}};var bu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),fe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var wu=require("jose");var hi,Ru=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!hi)try{hi=await(0,wu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return fe(n,e,{issuer:t.authUrl,secret:hi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Tu=et(ze());var Eu=et(ze());var dr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},yi=class extends dr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},bi=class extends dr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function yp(n,e){if(Ms(n))throw new yi(e)}i(yp,"throwIfUndefinedOrNull");function en(n,e){if(yp(n,e),!xe(n))throw new bi(e,"string")}i(en,"throwIfNotString");var pr=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return en(e,"redisClientUrl"),en(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){en(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Q("Rate limiting service failed with 401: Unauthorized"):new Q(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},mr=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(en(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Q("The in-memory redis client only supports /rate-limit calls")}};var bp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),fr=i(async n=>({key:`ip-${bp(n)}`}),"getIP"),hr=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),yr=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),gr;function br(n,e){let t;if(gr)return gr;if(g.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new mr,gr=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!xe(o))throw new Q(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!xe(r))throw new Q(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=pr.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Q(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return gr=t,t}i(br,"getRedisClient");async function wr(n,e,t,r,o){let s=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:n}),requestId:o})}i(wr,"getCountAndUpdateExpiry");function Rr(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await t(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new L(c)}return u},"outerFunction")}i(Rr,"wrapUserFunction");var Pr="Retry-After";var Pu=(0,Eu.debug)("zuplo:policies:RateLimitInboundPolicy"),Iu=i(async(n,e,t,r)=>{let o=ne.getLogger(e),s=i((P,D)=>{let z={};return(!P||P==="retry-after")&&(z[Pr]=D.toString()),T.tooManyRequests(n,e,void 0,z)},"rateLimited"),u={function:Rr(t,r),user:hr,ip:fr,all:yr}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,h=t.headerMode??"retry-after",y=br(r,o),E=`bucket/${g.instance.build.BUILD_ID}/${r}/${l}`,C=await ge(r,void 0,t),Z=new de(C,e),N=wr(E,p,y,o,e.requestId),j;i(async()=>{let P=await N;if(P.count>d){let D=Date.now()+P.ttlSeconds*1e3;Z.put(E,D,P.ttlSeconds),Pu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${E}' (async mode)`),j=s(h,P.ttlSeconds)}},"asyncCheck")();let B=await Z.get(E);if(B!==void 0&&B>Date.now()){Pu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${E}' (async mode)`);let P=Math.round((B-Date.now())/1e3);return s(h,P)}return e.addResponseSendingHook(async P=>j??P),n},"AsyncRateLimitInboundPolicy");var xu=(0,Tu.debug)("zuplo:policies:RateLimitInboundPolicy"),wp="strict",wi=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??wp)==="async")return Iu(n,e,t,r);let s=Date.now(),a=ne.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Pr]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Rr(t,r),user:hr,ip:fr,all:yr}[t.rateLimitBy],p=await d(n,e,r),h=p.key,y=p.requestsAllowed??t.requestsAllowed,_=p.timeWindowMinutes??t.timeWindowMinutes,E=t.headerMode??"retry-after",C=br(r,a),N=`bucket/${g.instance.build.BUILD_ID}/${r}/${h}`,j=await wr(N,_,C,a,e.requestId);return j.count>y?(xu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(E,j.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;xu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Ri;function vu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(vu,"headersToNameValuePairs");function Rp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Rp,"queryToNameValueParis");function Pp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Pp,"parseIntOrUndefined");var Su={};async function Ou(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return Ri||(Ri={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Ri,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:vu(n.headers),queryString:Rp(n.query)},response:{status:a.status,statusText:a.statusText,headers:vu(a.headers),content:{size:Pp(n.headers.get("content-length"))}}}]}}},d=Su[t.apiKey];if(!d){let p=t.apiKey;d=new X("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",_=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});_.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${_.status}: '${await _.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Su[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ou,"ReadmeMetricsInboundPolicy");var Cu=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Au=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var _u=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Lu=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ku=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Nu=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?ku():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ku():n},"RequestSizeLimitInboundPolicy");function Mu(n,e,t){return`_${Qe(n+"_"+e+"_"+t)}`}i(Mu,"getRawOperationDataIdentifierName");function Er(n,e,t,r){return`_${Qe(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Er,"getIdForParameterSchema");function Ir(n,e,t){return`_${Qe(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Qe(t.toLowerCase())}`}i(Ir,"getIdForRequestBodySchema");function Du(n,e){return`_${Qe(n)}__${Qe(e)}`}i(Du,"getIdForRefSchema");function Qe(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);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(n.charAt(t)):e.push("_")}return e.join("")}i(Qe,"sanitizedIdentifierName");var kt=i(n=>{let e=n.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"),Nt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Er(t,r,o,c.name),p=he.instance.schemaValidator[d],h=p(e[c.name]),y=Pi(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Pi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Uu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let _=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=T.badRequest(e,n,{detail:`${_}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",_,[r],y),Ne(t.validateBody))return E}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,_=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?_:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Ir(n.route.path,e.method,o),u=he.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,_=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?_:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Pi(l),h=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return h}i(Uu,"handleBodyValidation");function Hu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=kt(n),s=Nt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Hu,"handleHeadersValidation");function Zu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=kt(n),o=Nt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Zu,"handlePathParameterValidation");function qu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=kt(n),o=Nt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(qu,"handleQueryParameterValidation");var Ei=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=qu(e,n,t);if(r!==void 0||(r=Zu(e,n,t),r!==void 0)||(r=Hu(e,n,t),r!==void 0))return r;let o=await Uu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Fu=Ei;var $u=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ju=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Bu=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var zu=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Vu=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Gu=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!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(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Ep=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Wu=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ep(t.sleepInMs),n},"SleepInboundPolicy");var Ju=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),ie(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await fe(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new Q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Ku=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),ie(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await Ip(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Ip(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ee({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(Ip,"getAccessToken");var Yu="https://accounts.google.com/o/oauth2/token",Ii,Xu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),ie(t,r).required("serviceAccountJson","string"),Ii||(Ii=await Te.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ii,audience:Yu,payload:o}),l=await On(Yu,c,{retries:t.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)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var xp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Tp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],xi,Qu=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),ie(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Tp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}xi||(xi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await tr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:xi,audience:xp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Xs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ti,ec=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),ie(t,r).required("audience","string").required("serviceAccountJson","string"),Ti||(Ti=await Te.init(t.serviceAccountJson));let o=await De({serviceAccount:Ti,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var tc="https://www.googleapis.com/oauth2/v4/token",vi,nc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),ie(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),vi||(vi=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=at(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:vi,audience:tc,payload:o}),l=await On(tc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.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-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var rc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new Q("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var oc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((E,C)=>e(E,"name",{value:C,configurable:!0}),"__name"),o=i((E,C)=>i(function(){return C||(0,E[t(E)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(E){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,j){return j},attributeValueProcessor:function(N,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,j,q){return N}},Z=r(function(N){return Object.assign({},C,N)},"buildOptions");E.buildOptions=Z,E.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(E){"use strict";var C=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Z=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+Z+"]*",j=new RegExp("^"+N+"$"),q=r(function(P,D){let z=[],W=D.exec(P);for(;W;){let S=[];S.startIndex=D.lastIndex-W[0].length;let x=W.length;for(let H=0;H<x;H++)S.push(W[H]);z.push(S),W=D.exec(P)}return z},"getAllMatches"),B=r(function(P){let D=j.exec(P);return!(D===null||typeof D>"u")},"isName");E.isExist=function(P){return typeof P<"u"},E.isEmptyObject=function(P){return Object.keys(P).length===0},E.merge=function(P,D,z){if(D){let W=Object.keys(D),S=W.length;for(let x=0;x<S;x++)z==="strict"?P[W[x]]=[D[W[x]]]:P[W[x]]=D[W[x]]}},E.getValue=function(P){return E.isExist(P)?P:""},E.isName=B,E.getAllMatches=q,E.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(E,C){"use strict";var Z=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,j){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:j})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=Z}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(E,C){var Z=a();function N(S,x){let H={};if(S[x+3]==="O"&&S[x+4]==="C"&&S[x+5]==="T"&&S[x+6]==="Y"&&S[x+7]==="P"&&S[x+8]==="E"){x=x+9;let ce=1,Y=!1,ee=!1,Se="";for(;x<S.length;x++)if(S[x]==="<"&&!ee){if(Y&&B(S,x))x+=7,[entityName,val,x]=j(S,x+1),val.indexOf("&")===-1&&(H[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(Y&&P(S,x))x+=8;else if(Y&&D(S,x))x+=8;else if(Y&&z(S,x))x+=9;else if(q)ee=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(S[x]===">"){if(ee?S[x-1]==="-"&&S[x-2]==="-"&&(ee=!1,ce--):ce--,ce===0)break}else S[x]==="["?Y=!0:Se+=S[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}i(N,"readDocType"),r(N,"readDocType");function j(S,x){let H="";for(;x<S.length&&S[x]!=="'"&&S[x]!=='"';x++)H+=S[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[x++],Y="";for(;x<S.length&&S[x]!==ce;x++)Y+=S[x];return[H,Y,x]}i(j,"readEntityExp"),r(j,"readEntityExp");function q(S,x){return S[x+1]==="!"&&S[x+2]==="-"&&S[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function B(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="N"&&S[x+4]==="T"&&S[x+5]==="I"&&S[x+6]==="T"&&S[x+7]==="Y"}i(B,"isEntity"),r(B,"isEntity");function P(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="L"&&S[x+4]==="E"&&S[x+5]==="M"&&S[x+6]==="E"&&S[x+7]==="N"&&S[x+8]==="T"}i(P,"isElement"),r(P,"isElement");function D(S,x){return S[x+1]==="!"&&S[x+2]==="A"&&S[x+3]==="T"&&S[x+4]==="T"&&S[x+5]==="L"&&S[x+6]==="I"&&S[x+7]==="S"&&S[x+8]==="T"}i(D,"isAttlist"),r(D,"isAttlist");function z(S,x){return S[x+1]==="!"&&S[x+2]==="N"&&S[x+3]==="O"&&S[x+4]==="T"&&S[x+5]==="A"&&S[x+6]==="T"&&S[x+7]==="I"&&S[x+8]==="O"&&S[x+9]==="N"}i(z,"isNotation"),r(z,"isNotation");function W(S){if(Z.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(E,C){var Z=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(P,D={}){if(D=Object.assign({},j,D),!P||typeof P!="string")return P;let z=P.trim();if(D.skipLike!==void 0&&D.skipLike.test(z))return P;if(D.hex&&Z.test(z))return Number.parseInt(z,16);{let W=N.exec(z);if(W){let S=W[1],x=W[2],H=B(W[3]),ce=W[4]||W[6];if(!D.leadingZeros&&x.length>0&&S&&z[2]!==".")return P;if(!D.leadingZeros&&x.length>0&&!S&&z[1]!==".")return P;{let Y=Number(z),ee=""+Y;return ee.search(/[eE]/)!==-1||ce?D.eNotation?Y:P:z.indexOf(".")!==-1?ee==="0"&&H===""||ee===H||S&&ee==="-"+H?Y:P:x?H===ee||S+H===ee?Y:P:z===ee||z===S+ee?Y:P}}else return P}}i(q,"toNumber"),r(q,"toNumber");function B(P){return P&&P.indexOf(".")!==-1&&(P=P.replace(/0+$/,""),P==="."?P="0":P[0]==="."?P="0"+P:P[P.length-1]==="."&&(P=P.substr(0,P.length-1))),P}i(B,"trimZeros"),r(B,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(E,C){"use strict";var Z=a(),N=u(),j=c(),q=l(),B=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=P,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=z,this.buildAttributesMap=S,this.isItStopNode=ee,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=Y,this.addChild=H}};function P(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let V=I[A];this.lastEntities[V]={regex:new RegExp("&"+V+";","g"),val:R[V]}}}i(P,"addExternalEntities"),r(P,"addExternalEntities");function D(R,I,A,V,k,M,te){if(R!==void 0&&(this.options.trimValues&&!V&&(R=R.trim()),R.length>0)){te||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(I,R,A,k,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?le(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?le(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(D,"parseTextData"),r(D,"parseTextData");function z(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}i(z,"resolveNameSpace"),r(z,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let V=Z.getAllMatches(R,W),k=V.length,M={};for(let te=0;te<k;te++){let $=this.resolveNameSpace(V[te][1]),U=V[te][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let oe=this.options.attributeValueProcessor($,U,I);oe==null?M[ae]=U:typeof oe!=typeof U||oe!==U?M[ae]=oe:M[ae]=le(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=M,te}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
|
|
72
|
+
`);let I=new N("!xml"),A=I,V="",k="";for(let M=0;M<R.length;M++)if(R[M]==="<")if(R[M+1]==="/"){let $=b(R,">",M,"Closing Tag is not closed."),U=R.substring(M+2,$).trim();if(this.options.removeNSPrefix){let Ae=U.indexOf(":");Ae!==-1&&(U=U.substr(Ae+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),A&&(V=this.saveTextToParentTag(V,A,k));let ae=k.substring(k.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let oe=0;ae&&this.options.unpairedTags.indexOf(ae)!==-1?(oe=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=k.lastIndexOf("."),k=k.substring(0,oe),A=this.tagsNodeStack.pop(),V="",M=$}else if(R[M+1]==="?"){let $=O(R,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(V=this.saveTextToParentTag(V,A,k),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new N($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,k,$.tagName)),this.addChild(A,U,k)}M=$.closeIndex+1}else if(R.substr(M+1,3)==="!--"){let $=b(R,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let U=R.substring(M+4,$-2);V=this.saveTextToParentTag(V,A,k),A.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}M=$}else if(R.substr(M+1,2)==="!D"){let $=j(R,M);this.docTypeEntities=$.entities,M=$.i}else if(R.substr(M+1,2)==="!["){let $=b(R,"]]>",M,"CDATA is not closed.")-2,U=R.substring(M+9,$);V=this.saveTextToParentTag(V,A,k);let ae=this.parseTextData(U,A.tagname,k,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):A.add(this.options.textNodeName,ae),M=$+2}else{let $=O(R,M,this.options.removeNSPrefix),U=$.tagName,ae=$.rawTagName,oe=$.tagExp,Ae=$.attrExpPresent,Oi=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),A&&V&&A.tagname!=="!xml"&&(V=this.saveTextToParentTag(V,A,k,!1));let Ci=A;if(Ci&&this.options.unpairedTags.indexOf(Ci.tagname)!==-1&&(A=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),U!==I.tagname&&(k+=k?"."+U:U),this.isItStopNode(this.options.stopNodes,k,U)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)M=$.closeIndex;else{let kr=this.readStopNodeData(R,ae,Oi+1);if(!kr)throw new Error(`Unexpected end of ${ae}`);M=kr.i,Oe=kr.tagContent}let Lr=new N(U);U!==oe&&Ae&&(Lr[":@"]=this.buildAttributesMap(oe,k,U)),Oe&&(Oe=this.parseTextData(Oe,U,k,!0,Ae,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Lr.add(this.options.textNodeName,Oe),this.addChild(A,Lr,k)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),k=k.substr(0,k.length-1),oe=U):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Oe=new N(U);U!==oe&&Ae&&(Oe[":@"]=this.buildAttributesMap(oe,k,U)),this.addChild(A,Oe,k),k=k.substr(0,k.lastIndexOf("."))}else{let Oe=new N(U);this.tagsNodeStack.push(A),U!==oe&&Ae&&(Oe[":@"]=this.buildAttributesMap(oe,k,U)),this.addChild(A,Oe,k),A=Oe}V="",M=Oi}}else V+=R[M];return I.child},"parseXml");function H(R,I,A){let V=this.options.updateTag(I.tagname,A,I[":@"]);V===!1||(typeof V=="string"&&(I.tagname=V),R.addChild(I))}i(H,"addChild"),r(H,"addChild");var ce=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function Y(R,I,A,V){return R&&(V===void 0&&(V=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,V),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(Y,"saveTextToParentTag"),r(Y,"saveTextToParentTag");function ee(R,I,A){let V="*."+A;for(let k in R){let M=R[k];if(V===M||I===M)return!0}return!1}i(ee,"isItStopNode"),r(ee,"isItStopNode");function Se(R,I,A=">"){let V,k="";for(let M=I;M<R.length;M++){let te=R[M];if(V)te===V&&(V="");else if(te==='"'||te==="'")V=te;else if(te===A[0])if(A[1]){if(R[M+1]===A[1])return{data:k,index:M}}else return{data:k,index:M};else te===" "&&(te=" ");k+=te}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function b(R,I,A,V){let k=R.indexOf(I,A);if(k===-1)throw new Error(V);return k+I.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(R,I,A,V=">"){let k=Se(R,I+1,V);if(!k)return;let M=k.data,te=k.index,$=M.search(/\s/),U=M,ae=!0;$!==-1&&(U=M.substring(0,$),M=M.substring($+1).trimStart());let oe=U;if(A){let Ae=U.indexOf(":");Ae!==-1&&(U=U.substr(Ae+1),ae=U!==k.data.substr(Ae+1))}return{tagName:U,tagExp:M,closeIndex:te,attrExpPresent:ae,rawTagName:oe}}i(O,"readTagExp"),r(O,"readTagExp");function G(R,I,A){let V=A,k=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let M=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,M).trim()===I&&(k--,k===0))return{tagContent:R.substring(V,A),i:M};A=M}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let M=O(R,A,">");M&&((M&&M.tagName)===I&&M.tagExp[M.tagExp.length-1]!=="/"&&k++,A=M.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function le(R,I,A){if(I&&typeof R=="string"){let V=R.trim();return V==="true"?!0:V==="false"?!1:q(R,A)}else return Z.isExist(R)?R:""}i(le,"parseValue"),r(le,"parseValue"),C.exports=B}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(E){"use strict";function C(B,P){return Z(B,P)}i(C,"prettify"),r(C,"prettify");function Z(B,P,D){let z,W={};for(let S=0;S<B.length;S++){let x=B[S],H=N(x),ce="";if(D===void 0?ce=H:ce=D+"."+H,H===P.textNodeName)z===void 0?z=x[H]:z+=""+x[H];else{if(H===void 0)continue;if(x[H]){let Y=Z(x[H],P,ce),ee=q(Y,P);x[":@"]?j(Y,x[":@"],ce,P):Object.keys(Y).length===1&&Y[P.textNodeName]!==void 0&&!P.alwaysCreateTextNode?Y=Y[P.textNodeName]:Object.keys(Y).length===0&&(P.alwaysCreateTextNode?Y[P.textNodeName]="":Y=""),W[H]!==void 0&&W.hasOwnProperty(H)?(Array.isArray(W[H])||(W[H]=[W[H]]),W[H].push(Y)):P.isArray(H,ce,ee)?W[H]=[Y]:W[H]=Y}}}return typeof z=="string"?z.length>0&&(W[P.textNodeName]=z):z!==void 0&&(W[P.textNodeName]=z),W}i(Z,"compress"),r(Z,"compress");function N(B){let P=Object.keys(B);for(let D=0;D<P.length;D++){let z=P[D];if(z!==":@")return z}}i(N,"propName"),r(N,"propName");function j(B,P,D,z){if(P){let W=Object.keys(P),S=W.length;for(let x=0;x<S;x++){let H=W[x];z.isArray(H,D+"."+H,!0,!0)?B[H]=[P[H]]:B[H]=P[H]}}}i(j,"assignAttributes"),r(j,"assignAttributes");function q(B,P){let{textNodeName:D}=P,z=Object.keys(B).length;return!!(z===0||z===1&&(B[D]||typeof B[D]=="boolean"||B[D]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),E.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(E){"use strict";var C=a(),Z={allowBooleanAttributes:!1,unpairedTags:[]};E.validate=function(b,O){O=Object.assign({},Z,O);let G=[],le=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let V=!1;b[I]==="/"&&(V=!0,I++);let k="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
|
|
73
|
+
`&&b[I]!=="\r";I++)k+=b[I];if(k=k.trim(),k[k.length-1]==="/"&&(k=k.substring(0,k.length-1),I--),!Y(k)){let $;return k.trim().length===0?$="Invalid space after '<'.":$="Tag '"+k+"' is an invalid name.",H("InvalidTag",$,ee(b,I))}let M=D(b,I);if(M===!1)return H("InvalidAttr","Attributes for '"+k+"' have open quote.",ee(b,I));let te=M.value;if(I=M.index,te[te.length-1]==="/"){let $=I-te.length;te=te.substring(0,te.length-1);let U=W(te,O);if(U===!0)le=!0;else return H(U.err.code,U.err.msg,ee(b,$+U.err.line))}else if(V)if(M.tagClosed){if(te.trim().length>0)return H("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",ee(b,A));{let $=G.pop();if(k!==$.tagName){let U=ee(b,$.tagStartPos);return H("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+k+"'.",ee(b,A))}G.length==0&&(R=!0)}}else return H("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",ee(b,I));else{let $=W(te,O);if($!==!0)return H($.err.code,$.err.msg,ee(b,I-te.length+$.err.line));if(R===!0)return H("InvalidXml","Multiple possible root nodes found.",ee(b,I));O.unpairedTags.indexOf(k)!==-1||G.push({tagName:k,tagStartPos:A}),le=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let $=x(b,I);if($==-1)return H("InvalidChar","char '&' is not expected.",ee(b,I));I=$}else if(R===!0&&!N(b[I]))return H("InvalidXml","Extra text at the end",ee(b,I));b[I]==="<"&&I--}}else{if(N(b[I]))continue;return H("InvalidChar","char '"+b[I]+"' is not expected.",ee(b,I))}if(le){if(G.length==1)return H("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",ee(b,G[0].tagStartPos));if(G.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(G.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
|
|
74
|
+
`||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function j(b,O){let G=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let le=b.substr(G,O-G);if(O>5&&le==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",ee(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(j,"readPI"),r(j,"readPI");function q(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let G=1;for(O+=8;O<b.length;O++)if(b[O]==="<")G++;else if(b[O]===">"&&(G--,G===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var B='"',P="'";function D(b,O){let G="",le="",R=!1;for(;O<b.length;O++){if(b[O]===B||b[O]===P)le===""?le=b[O]:le!==b[O]||(le="");else if(b[O]===">"&&le===""){R=!0;break}G+=b[O]}return le!==""?!1:{value:G,index:O,tagClosed:R}}i(D,"readAttributeStr"),r(D,"readAttributeStr");var z=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,O){let G=C.getAllMatches(b,z),le={};for(let R=0;R<G.length;R++){if(G[R][1].length===0)return H("InvalidAttr","Attribute '"+G[R][2]+"' has no space in starting.",Se(G[R]));if(G[R][3]!==void 0&&G[R][4]===void 0)return H("InvalidAttr","Attribute '"+G[R][2]+"' is without value.",Se(G[R]));if(G[R][3]===void 0&&!O.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+G[R][2]+"' is not allowed.",Se(G[R]));let I=G[R][2];if(!ce(I))return H("InvalidAttr","Attribute '"+I+"' is an invalid name.",Se(G[R]));if(!le.hasOwnProperty(I))le[I]=1;else return H("InvalidAttr","Attribute '"+I+"' is repeated.",Se(G[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(b,O){let G=/\d/;for(b[O]==="x"&&(O++,G=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(G))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function x(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,S(b,O);let G=0;for(;O<b.length;O++,G++)if(!(b[O].match(/\w/)&&G<20)){if(b[O]===";")break;return-1}return O}i(x,"validateAmpersand"),r(x,"validateAmpersand");function H(b,O,G){return{err:{code:b,msg:O,line:G.line||G,col:G.col}}}i(H,"getErrorObject"),r(H,"getErrorObject");function ce(b){return C.isName(b)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function Y(b){return C.isName(b)}i(Y,"validateTagName"),r(Y,"validateTagName");function ee(b,O){let G=b.substring(0,O).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(ee,"getLineNumberForPosition"),r(ee,"getLineNumberForPosition");function Se(b){return b.startIndex+b[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(E,C){var{buildOptions:Z}=s(),N=d(),{prettify:j}=p(),q=h(),B=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(P){this.externalEntities={},this.options=Z(P)}parse(P,D){if(typeof P!="string")if(P.toString)P=P.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(D){D===!0&&(D={});let S=q.validate(P,D);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let z=new N(this.options);z.addExternalEntities(this.externalEntities);let W=z.parseXml(P);return this.options.preserveOrder||W===void 0?W:j(W,this.options)}addEntity(P,D){if(D.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(P.indexOf("&")!==-1||P.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(D==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[P]=D}};C.exports=B}});let _=y();return new _(n)},"getXmlParser");var xr=class extends Fe{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),ie(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?bt(e.parseOnStatusCodes):void 0,this.parser=oc({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,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Tr=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){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,t)}getService(e){return this.services.get(e)}};var vr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new X(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Hn().waitUntil(this.#e.waitUntilFlushed())}};var ic=10,sc=3e4,Sr=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=sc,this.#r=ic}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:sc,this.#r=ic}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await vp(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Hn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function vp(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(vp,"waitUntilTrue");var Si=["sha-1","sha-256","sha-384","sha-512"],Or=class{static{i(this,"BaseCryptoBeta")}};var Cr=class extends Or{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!Si.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${Si.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Ar=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var _r=class extends Ar{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new un("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
75
75
|
/*! For license information please see index.js.LEGAL.txt */
|