@zuplo/runtime 5.1760.0 → 5.1761.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +6 -1
- package/index.minified.js +16 -16
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -99,7 +99,6 @@ declare interface AmberfloMeteringProperties extends Omit<AmberfloMeteringIngest
|
|
|
99
99
|
*
|
|
100
100
|
* @title API Key Authentication
|
|
101
101
|
* @public
|
|
102
|
-
* @unlisted
|
|
103
102
|
* @param request - The ZuploRequest
|
|
104
103
|
* @param context - The ZuploContext
|
|
105
104
|
* @param unparsedOptions - The policy options set in policies.json
|
|
@@ -724,6 +723,12 @@ declare interface CompatibilityFlags {
|
|
|
724
723
|
* @compatibilityDate 2024-01-15
|
|
725
724
|
*/
|
|
726
725
|
runOutboundPoliciesOnHandlerOnAllStatuses: boolean;
|
|
726
|
+
/**
|
|
727
|
+
* Whether or not hooks run on system routes
|
|
728
|
+
*
|
|
729
|
+
* @compatibilityDate 2024-01-15
|
|
730
|
+
*/
|
|
731
|
+
doNotRunHooksOnSystemRoutes: boolean;
|
|
727
732
|
}
|
|
728
733
|
|
|
729
734
|
/**
|
package/index.minified.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 t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(
|
|
25
|
+
"use strict";var ca=Object.create;var je=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var da=Object.getOwnPropertyNames;var pa=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var s=(t,e)=>je(t,"name",{value:e,configurable:!0});var ze=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ga=(t,e)=>{for(var n in e)je(t,n,{get:e[n],enumerable:!0})},no=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of da(e))!ma.call(t,o)&&o!==n&&je(t,o,{get:()=>e[o],enumerable:!(r=la(e,o))||r.enumerable});return t};var Oe=(t,e,n)=>(n=t!=null?ca(pa(t)):{},no(e||!t||!t.__esModule?je(n,"default",{value:t,enumerable:!0}):n,t)),fa=t=>no(je({},"__esModule",{value:!0}),t);var xo=ze(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.generateColor=b.colorFunctions=b.stripColor=b.bgRgb24=b.rgb24=b.bgRgb8=b.rgb8=b.bgBrightWhite=b.bgBrightCyan=b.bgBrightMagenta=b.bgBrightBlue=b.bgBrightYellow=b.bgBrightGreen=b.bgBrightRed=b.bgBrightBlack=b.bgWhite=b.bgCyan=b.bgMagenta=b.bgBlue=b.bgYellow=b.bgGreen=b.bgRed=b.bgBlack=b.brightWhite=b.brightCyan=b.brightMagenta=b.brightBlue=b.brightYellow=b.brightGreen=b.brightRed=b.brightBlack=b.gray=b.white=b.cyan=b.magenta=b.blue=b.yellow=b.green=b.red=b.black=b.strikethrough=b.hidden=b.inverse=b.underline=b.italic=b.dim=b.bold=b.reset=b.getColorEnabled=b.setColorEnabled=void 0;var ho=!0,Nn=!ho;function ha(t){ho||(Nn=t)}s(ha,"setColorEnabled");b.setColorEnabled=ha;function ya(){return Nn}s(ya,"getColorEnabled");b.getColorEnabled=ya;function v(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(v,"code");function O(t,e){return Nn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function ba(t){return O(t,v([0],0))}s(ba,"reset");b.reset=ba;function wa(t){return O(t,v([1],22))}s(wa,"bold");b.bold=wa;function Ra(t){return O(t,v([2],22))}s(Ra,"dim");b.dim=Ra;function Pa(t){return O(t,v([3],23))}s(Pa,"italic");b.italic=Pa;function Ea(t){return O(t,v([4],24))}s(Ea,"underline");b.underline=Ea;function Ia(t){return O(t,v([7],27))}s(Ia,"inverse");b.inverse=Ia;function xa(t){return O(t,v([8],28))}s(xa,"hidden");b.hidden=xa;function va(t){return O(t,v([9],29))}s(va,"strikethrough");b.strikethrough=va;function Oa(t){return O(t,v([30],39))}s(Oa,"black");b.black=Oa;function yo(t){return O(t,v([31],39))}s(yo,"red");b.red=yo;function bo(t){return O(t,v([32],39))}s(bo,"green");b.green=bo;function wo(t){return O(t,v([33],39))}s(wo,"yellow");b.yellow=wo;function Ro(t){return O(t,v([34],39))}s(Ro,"blue");b.blue=Ro;function Po(t){return O(t,v([35],39))}s(Po,"magenta");b.magenta=Po;function Eo(t){return O(t,v([36],39))}s(Eo,"cyan");b.cyan=Eo;function Ta(t){return O(t,v([37],39))}s(Ta,"white");b.white=Ta;function Sa(t){return Io(t)}s(Sa,"gray");b.gray=Sa;function Io(t){return O(t,v([90],39))}s(Io,"brightBlack");b.brightBlack=Io;function Ca(t){return O(t,v([91],39))}s(Ca,"brightRed");b.brightRed=Ca;function Aa(t){return O(t,v([92],39))}s(Aa,"brightGreen");b.brightGreen=Aa;function La(t){return O(t,v([93],39))}s(La,"brightYellow");b.brightYellow=La;function _a(t){return O(t,v([94],39))}s(_a,"brightBlue");b.brightBlue=_a;function ka(t){return O(t,v([95],39))}s(ka,"brightMagenta");b.brightMagenta=ka;function Da(t){return O(t,v([96],39))}s(Da,"brightCyan");b.brightCyan=Da;function Ha(t){return O(t,v([97],39))}s(Ha,"brightWhite");b.brightWhite=Ha;function Ua(t){return O(t,v([40],49))}s(Ua,"bgBlack");b.bgBlack=Ua;function Na(t){return O(t,v([41],49))}s(Na,"bgRed");b.bgRed=Na;function Ma(t){return O(t,v([42],49))}s(Ma,"bgGreen");b.bgGreen=Ma;function Za(t){return O(t,v([43],49))}s(Za,"bgYellow");b.bgYellow=Za;function qa(t){return O(t,v([44],49))}s(qa,"bgBlue");b.bgBlue=qa;function $a(t){return O(t,v([45],49))}s($a,"bgMagenta");b.bgMagenta=$a;function Fa(t){return O(t,v([46],49))}s(Fa,"bgCyan");b.bgCyan=Fa;function Ba(t){return O(t,v([47],49))}s(Ba,"bgWhite");b.bgWhite=Ba;function ja(t){return O(t,v([100],49))}s(ja,"bgBrightBlack");b.bgBrightBlack=ja;function za(t){return O(t,v([101],49))}s(za,"bgBrightRed");b.bgBrightRed=za;function Va(t){return O(t,v([102],49))}s(Va,"bgBrightGreen");b.bgBrightGreen=Va;function Ga(t){return O(t,v([103],49))}s(Ga,"bgBrightYellow");b.bgBrightYellow=Ga;function Wa(t){return O(t,v([104],49))}s(Wa,"bgBrightBlue");b.bgBrightBlue=Wa;function Ka(t){return O(t,v([105],49))}s(Ka,"bgBrightMagenta");b.bgBrightMagenta=Ka;function Ja(t){return O(t,v([106],49))}s(Ja,"bgBrightCyan");b.bgBrightCyan=Ja;function Ya(t){return O(t,v([107],49))}s(Ya,"bgBrightWhite");b.bgBrightWhite=Ya;function de(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(de,"clampAndTruncate");function Qa(t,e){return O(t,v([38,5,de(e)],39))}s(Qa,"rgb8");b.rgb8=Qa;function Xa(t,e){return O(t,v([48,5,de(e)],49))}s(Xa,"bgRgb8");b.bgRgb8=Xa;function eu(t,e){return typeof e=="number"?O(t,v([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,v([38,2,de(e.r),de(e.g),de(e.b)],39))}s(eu,"rgb24");b.rgb24=eu;function tu(t,e){return typeof e=="number"?O(t,v([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,v([48,2,de(e.r),de(e.g),de(e.b)],49))}s(tu,"bgRgb24");b.bgRgb24=tu;var nu=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 ru(t){return t.replace(nu,"")}s(ru,"stripColor");b.stripColor=ru;b.colorFunctions=[yo,bo,wo,Ro,Po,Eo];function ou(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}s(ou,"hashCode");function iu(t){let e=Math.abs(ou(t));return b.colorFunctions[e%b.colorFunctions.length]}s(iu,"generateColor");b.generateColor=iu});var vo=ze(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.format=void 0;function su(t,e,...n){let r=0,o=n.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
|
|
26
|
+
`).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(su,"format");gt.format=su});var Lo=ze(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.inspect=void 0;function we(t,e,n,r){let o={seen:[],stylize:au,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=cu),ft(o,t,o.depth)}s(we,"inspect");ht.inspect=we;we.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]};we.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function au(t,e){return t}s(au,"stylizeNoColor");function uu(t){return typeof t=="boolean"}s(uu,"isBoolean");function To(t){return t===void 0}s(To,"isUndefined");function cu(t,e){let n=we.styles[e];return n?"\x1B["+we.colors[n][0]+"m"+t+"\x1B["+we.colors[n][1]+"m":t}s(cu,"stylizeWithColor");function Mn(t){return typeof t=="function"}s(Mn,"isFunction");function So(t){return typeof t=="string"}s(So,"isString");function lu(t){return typeof t=="number"}s(lu,"isNumber");function Co(t){return t===null}s(Co,"isNull");function Ao(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Ao,"hasOwn");function Zn(t){return Bn(t)&&jn(t)==="[object RegExp]"}s(Zn,"isRegExp");function Bn(t){return typeof t=="object"&&t!==null}s(Bn,"isObject");function qn(t){return Bn(t)&&(jn(t)==="[object Error]"||t instanceof Error)}s(qn,"isError");function Oo(t){return Bn(t)&&jn(t)==="[object Date]"}s(Oo,"isDate");function jn(t){return Object.prototype.toString.call(t)}s(jn,"objectToString");function du(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(du,"arrayToHash");function pu(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)Ao(e,String(a))?i.push(Fn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Fn(t,e,n,r,a,!0))}),i}s(pu,"formatArray");function $n(t){return"["+Error.prototype.toString.call(t)+"]"}s($n,"formatError");function ft(t,e,n){if(t.customInspect&&e&&Mn(e.inspect)&&e.inspect!==we&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return So(d)||(d=ft(t,d,n)),d}let r=mu(t,e);if(r)return r;let o=Object.keys(e),i=du(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(qn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return $n(e);if(o.length===0){if(Mn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Zn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Oo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(qn(e))return $n(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Mn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Zn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Oo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),qn(e)&&(a=" "+$n(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Zn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=pu(t,e,n,i,o):l=o.map(function(d){return Fn(t,e,n,i,d,u)}),t.seen.pop(),gu(l,a,c)}s(ft,"formatValue");function Fn(t,e,n,r,o,i){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),Ao(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Co(n)?u=ft(t,c.value,null):u=ft(t,c.value,n-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(i?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
29
29
|
`).substr(2):u=`
|
|
30
30
|
`+u.split(`
|
|
31
31
|
`).map(function(l){return" "+l}).join(`
|
|
32
|
-
`))):u=t.stylize("[Circular]","special")),
|
|
32
|
+
`))):u=t.stylize("[Circular]","special")),To(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}s(Fn,"formatProperty");function mu(t,e){if(To(e))return t.stylize("undefined","undefined");if(So(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(lu(e))return t.stylize(""+e,"number");if(uu(e))return t.stylize(""+e,"boolean");if(Co(e))return t.stylize("null","null")}s(mu,"formatPrimitive");function gu(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+t.join(`,
|
|
35
|
-
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(mu,"reduceToSingleString")});var Lo=je(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.format=void 0;var gu=xo(),fu=Ao(),hu=s((t,...e)=>(0,gu.format)(fu.inspect,t,e),"format");ht.format=hu});var Re=je(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.debug=pe.withoutEnv=pe.Debugger=void 0;var yu=Io(),bu=Lo(),yt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,yu.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,bu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};pe.Debugger=yt;var bt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function _o(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(_o,"extract");var Ge;function wu(t){t||(t=[]),typeof t=="string"&&(t=_o(t)),Ge=new bt(t)}s(wu,"withoutEnv");pe.withoutEnv=wu;function Ru(t){let e=globalThis.DEBUG;Ge||(Ge=new bt(_o(e)));let n=new yt(Ge,t);return Ge.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(Ru,"debug");pe.debug=Ru});var Il={};ma(Il,{API_KEY:()=>oi,AWSLoggingPlugin:()=>Yt,AmberfloMeteringInboundPolicy:()=>Wi,AmberfloMeteringPolicy:()=>on,ApiAuthKeyInboundPolicy:()=>Yi,ApiKeyInboundPolicy:()=>an,AuditLogDataStaxProvider:()=>en,AuditLogPlugin:()=>tn,Auth0JwtInboundPolicy:()=>Qi,AwsLambdaHandlerExtensions:()=>_i,BasicAuthInboundPolicy:()=>Xi,BasicRateLimitInboundPolicy:()=>jr,CachingInboundPolicy:()=>es,ChangeMethodInboundPolicy:()=>ts,ClearHeadersInboundPolicy:()=>ns,ClearHeadersOutboundPolicy:()=>rs,ClerkJwtInboundPolicy:()=>os,CognitoJwtInboundPolicy:()=>is,CompositeInboundPolicy:()=>ss,ConfigurationError:()=>g,ContentTypes:()=>Pt,ContextData:()=>le,CreditsMeteringInboundPolicy:()=>as,CryptoBeta:()=>yn,CurityPhantomTokenInboundPolicy:()=>us,DataDogLoggingPlugin:()=>Nt,DataDogMetricsPlugin:()=>Qt,DynaTraceLoggingPlugin:()=>Gt,DynatraceMetricsPlugin:()=>Xt,FirebaseJwtInboundPolicy:()=>cs,FormDataToJsonInboundPolicy:()=>ls,GeoFilterInboundPolicy:()=>ds,GoogleCloudLoggingPlugin:()=>Dt,Handler:()=>jt,HttpProblems:()=>R,HttpStatusCode:()=>xt,JWTScopeValidationInboundPolicy:()=>ps,KeyValueStore:()=>wn,LoadSubscriptionInboundPolicy:()=>ia,LokiLoggingPlugin:()=>Wt,LookupResult:()=>ke,MemoryZoneReadThroughCache:()=>N,MeteringInboundPolicy:()=>oa,MockApiInboundPolicy:()=>gs,MoesifInboundPolicy:()=>Rs,OktaJwtInboundPolicy:()=>Ps,OpenIdJwtInboundPolicy:()=>$,ProblemResponseFormatter:()=>me,PropelAuthJwtInboundPolicy:()=>Is,RateLimitInboundPolicy:()=>jr,ReadmeMetricsInboundPolicy:()=>Ss,RemoveHeadersInboundPolicy:()=>Cs,RemoveHeadersOutboundPolicy:()=>As,RemoveQueryParamsInboundPolicy:()=>Ls,ReplaceStringOutboundPolicy:()=>_s,RequestSizeLimitInboundPolicy:()=>Ds,RequestValidationInboundPolicy:()=>Wr,RequireOriginInboundPolicy:()=>Fs,ResponseSendingEvent:()=>Ce,ResponseSentEvent:()=>Ae,Router:()=>De,SYSTEM_LOGGER:()=>et,SchemaBasedRequestValidation:()=>$s,ServiceProviderImpl:()=>fn,SetBodyInboundPolicy:()=>Bs,SetHeadersInboundPolicy:()=>zs,SetHeadersOutboundPolicy:()=>js,SetQueryParamsInboundPolicy:()=>Vs,SetStatusOutboundPolicy:()=>Gs,SleepInboundPolicy:()=>Ws,StripeMeteringPlugin:()=>Nr,StripeWebhookVerificationInboundPolicy:()=>nn,SumoLogicLoggingPlugin:()=>Kt,SupabaseJwtInboundPolicy:()=>Ks,SystemLogMap:()=>S,SystemRouteName:()=>oe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Js,UpstreamFirebaseAdminAuthInboundPolicy:()=>Qs,UpstreamFirebaseUserAuthInboundPolicy:()=>Xs,UpstreamGcpJwtInboundPolicy:()=>ea,UpstreamGcpServiceAuthInboundPolicy:()=>na,VMWareLogInsightLoggingPlugin:()=>Jt,ValidateJsonSchemaInbound:()=>ra,ZoneCache:()=>re,ZuploRequest:()=>L,awsLambdaHandler:()=>ki,environment:()=>M,getIdForParameterSchema:()=>mn,getIdForRefSchema:()=>Us,getIdForRequestBodySchema:()=>gn,getRawOperationDataIdentifierName:()=>Hs,httpStatuses:()=>vt,isRestrictedEnvVariableName:()=>dr,isZuploReadableEnvVariableName:()=>pr,openApiSpecHandler:()=>Di,originalFetch:()=>He,purgeGatewayCache:()=>Pi,redirectHandler:()=>Hi,sanitizedIdentifierName:()=>be,serialize:()=>Et,setMoesifContext:()=>ws,urlForwardHandler:()=>Ui,urlRewriteHandler:()=>Ni,webSocketHandler:()=>Mi,webSocketPipelineHandler:()=>$i});module.exports=ga(Il);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},P=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends P{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},dt=class extends P{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new T("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var pt=globalThis,no=pt.caches;if(no){let t=no.open;pt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete pt.caches.default,Object.freeze(pt.caches)}var ro=new Map,Pn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Te=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=ro.get(e);r||(r=new Pn(n),ro.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var En="__zuplo-expiry-header",re=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(En);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(En,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(En,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var N=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Te(r),this.#n=new re(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var oo="zuplo-request-id",Ve="zp-rid",io="zp-body-removed",Se="cf-ray",In="cf-ipcity",xn="cf-ipcontinent",vn="cf-ipcountry",On="cf-iplongitude",Tn="cf-iplatitude",so="zp-ipcity",ao="zp-ipcontinent",uo="zp-ipcountry",co="zp-iplongitude",lo="zp-iplatitude",po="true-client-ip",Sn="zp-asn",Cn="zp-asorg",An="zp-colo",Ln="zp-postalcode",_n="zp-metrocode",kn="zp-region",Dn="zp-regioncode",Hn="zp-timezone",mo=[In,xn,vn,On,Tn,Sn,Cn,An,Ln,_n,kn,Dn,Hn],go=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];var pi=Oe(Re());var We=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new P("Error in custom 'problemResponseFormat'",{cause:i})}})}},me=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await We.problemResponseFormat(e,n,r)}};function wt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&wt(n)}return Object.freeze(t)}s(wt,"deepFreeze");var L=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return wt(this.#e)}get params(){return wt(this.#t)}user};var Pe=class{static{s(this,"RuntimePlugin")}},ue=class extends Pe{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ke={},ge=[],ko=[],Do=[],Ho=[];var Rt={addPlugin(t){ge.push(t)},addRequestHook(t){ko.push(t)},addResponseSendingHook(t){Do.push(t)},addResponseSendingFinalHook(t){Ho.push(t)}},Uo=s(async(t,e)=>{let n=t;for(let r of ko){let o=await r(n,e);if(o instanceof L)n=o;else{if(o instanceof Response)return o;throw new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),No=s(async(t,e,n)=>{let r=t;for(let o of Do){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Mo=s(async(t,e,n)=>{for(let r of Ho)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Zo(t=()=>Promise.resolve()){await t(Rt),Ke.value=Rt;for(let e of ge)e instanceof ue&&await e.initialize(Rt);We.setProblemResponseFormat(Rt.problemResponseFormat)}s(Zo,"initializeRuntime");var Pt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Et(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Pt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Pt.Json)||!e?JSON.stringify(t):t}s(Et,"serialize");var H=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async b=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async x=>{let A=await r(x,i);return Pu(A)},n)(b,i)},"nextPipe"),l=await u(o),d=new Ce(o,l);i.dispatchEvent(d);let p=F.getContextExtensions(i),h=p.latestRequest,m;try{m=await d.mutableResponse}catch(b){return i.log.error(b),n.errorHandler(o,i,b)}try{m=await p.onResponseSending(m,h,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}try{m=await No(m,h,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}i.dispatchEvent(new Ae(o,m));try{await p.onResponseSendingFinal(l,h,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Mo(l,h,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return m}};function Pu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Et(t),{headers:{"content-type":"application/json"}})}s(Pu,"resultToResponse");var fe=class extends Pe{static{s(this,"MetricsPlugin")}};var S=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new T(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var It=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,S.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=y.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();S.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Je.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Je={name:"__system-no-version",pathPrefix:""};var B=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Se)??void 0,c=t.headers.get(po)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=F.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new It(e)),ge.forEach(b=>{if(b instanceof fe){let E=b.getTransport();m.push(E)}}),m.forEach(b=>{b.pushMetrics(h,e)}),a},"metricsProcessor");var oe=(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))(oe||{});var zn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return R.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&S.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new H({processors:[B],handler:n,gateway:e}),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var xt=(f=>(f[f.CONTINUE=100]="CONTINUE",f[f.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",f[f.PROCESSING=102]="PROCESSING",f[f.EARLY_HINTS=103]="EARLY_HINTS",f[f.OK=200]="OK",f[f.CREATED=201]="CREATED",f[f.ACCEPTED=202]="ACCEPTED",f[f.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",f[f.NO_CONTENT=204]="NO_CONTENT",f[f.RESET_CONTENT=205]="RESET_CONTENT",f[f.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",f[f.MULTI_STATUS=207]="MULTI_STATUS",f[f.ALREADY_REPORTED=208]="ALREADY_REPORTED",f[f.IM_USED=226]="IM_USED",f[f.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",f[f.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",f[f.FOUND=302]="FOUND",f[f.SEE_OTHER=303]="SEE_OTHER",f[f.NOT_MODIFIED=304]="NOT_MODIFIED",f[f.USE_PROXY=305]="USE_PROXY",f[f.SWITCH_PROXY=306]="SWITCH_PROXY",f[f.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",f[f.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",f[f.BAD_REQUEST=400]="BAD_REQUEST",f[f.UNAUTHORIZED=401]="UNAUTHORIZED",f[f.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",f[f.FORBIDDEN=403]="FORBIDDEN",f[f.NOT_FOUND=404]="NOT_FOUND",f[f.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",f[f.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",f[f.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",f[f.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",f[f.CONFLICT=409]="CONFLICT",f[f.GONE=410]="GONE",f[f.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",f[f.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",f[f.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",f[f.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",f[f.URI_TOO_LONG=414]="URI_TOO_LONG",f[f.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",f[f.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",f[f.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",f[f.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",f[f.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",f[f.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",f[f.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",f[f.LOCKED=423]="LOCKED",f[f.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",f[f.TOO_EARLY=425]="TOO_EARLY",f[f.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",f[f.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",f[f.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",f[f.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",f[f.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",f[f.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",f[f.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",f[f.BAD_GATEWAY=502]="BAD_GATEWAY",f[f.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",f[f.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",f[f.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",f[f.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",f[f.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",f[f.LOOP_DETECTED=508]="LOOP_DETECTED",f[f.NOT_EXTENDED=510]="NOT_EXTENDED",f[f.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",f))(xt||{}),qo={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 Eu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},vt=Eu;function Iu(t){return`${new URL(t.url).pathname}`}s(Iu,"instance");function xu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(Se);return r&&(n.rayId=r),n}s(xu,"trace");var vu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Iu(e),trace:xu(e,n),...r},additionalHeaders:o,statusText:vt[t.status]}),"merge"),jn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?me.format(e,n,r):me.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:qo[e],...n}}},R=class extends jn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=vu(this.getProblemFromStatus(e),n,r,o,i);return me.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Ou}=Object.prototype,{propertyIsEnumerable:Tu}=Object.prototype;function Vn(t){return Ou.call(t)}s(Vn,"toString");function Q(t){return typeof t=="string"}s(Q,"isString");function Le(t){return Q(t)&&t!==""}s(Le,"isNonEmptyString");function $o(t){return Vn(t)==="[object RegExp]"}s($o,"isRegexp");function Fo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Tu.call(t,e))]}s(Fo,"getOwnEnumerableKeys");function Ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Ye,"isObject");function Gn(t){return typeof t=="number"&&!isNaN(t)}s(Gn,"isNumber");function Wn(t){return t===!0||t===!1}s(Wn,"isBoolean");function Bo(t){return typeof t>"u"}s(Bo,"isUndefined");function zo(t){return Bo(t)||t===null}s(zo,"isUndefinedOrNull");function Qe(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Qe,"isErrorLike");var jo=new Map;function Vo(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=jo.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return jo.set(t,r),r}s(Vo,"statusCodesStringToNumberArray");function Ee(t,e,n){if(!e.startsWith("."))throw new g(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new P(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ee,"getValueFromRequestUser");function Kn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new g("Received an array that contains non-string values.");return t}if(Q(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new g(`Expected type of string, received type '${typeof t}'`)}s(Kn,"parseValueToStringArray");function Go(t){if(t==null)return[];if(!Array.isArray(t))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Ye(n))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Le(n.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Gn(n.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Wn(n.allowCredentials))throw new g("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=Jn(n,"allowedHeaders"),o=Jn(n,"allowedMethods"),i=Jn(n,"exposeHeaders"),a;try{a=Kn(n.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(Go,"parseCorsPolicies");function Jn(t,e){let n;if(t[e]!==void 0)try{n=Kn(t[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Jn,"parseOptionalProperty");var Ot=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Tt=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Yn=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return R.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=t.lookup(l,c);if(!h)return R.notFound(a,u);let m=h.routeConfiguration,b=Su(l,d,p,m,n);return b.isValid?new Response(void 0,{status:200,statusText:"OK",headers:b.headers}):(b.error&&u.log.warn(b.error),R.notFound(a,u))},"optionsHandler"),o=new H({processors:[B],handler:r,gateway:e}),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Su=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ot(a.allowedOrigins,n);return u?{isValid:!0,headers:Tt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Wo=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new H({processors:[B],handler:n,gateway:e}),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Qn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ko=s((t,e)=>{let n=s(async(o,i)=>{let a=Ke.value?.notFoundHandler;if(a){let u=F.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new H({processors:[B],handler:n,gateway:e});t.addRoute(Qn,r.execute)},"registerNotMatchedHandler");var Cu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Jo=s(t=>{Cu.forEach(e=>t.delete(e))},"stripCorsHeaders"),St=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Jo(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new T(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Au(o,n.routeData.corsPolicies),u=Lu(t,a),c=new Headers(i.headers);return Jo(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Au=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new g(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Lu=s((t,e)=>{let n=Ot(e.allowedOrigins,t.headers.get("origin"));return n?Tt(e,n):{}},"getCorsHeaders");var Xn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new H({processors:[St],handler:n,gateway:e}),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function Xe(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new g(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new g(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Xe,"getInboundPolicyHandlerAndOptions");function _u(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new g(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(_u,"getOutboundPolicyHandlerAndOptions");var er=s(t=>async(e,n)=>{let r=F.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof L)i=u;else if(u instanceof Request)i=new L(u);else{if(u instanceof Response)return u;throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),ku=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Ct=s(async(t,e,n,r)=>{let o=Xe(e.route,n.routeData.policies),i=_u(e.route,n.routeData.policies);return Qo({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Yo({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Qo({request:r,context:o,inboundPolicies:t.map(u=>({...u,exportName:"default",policyName:u.handler.name})),outboundPolicies:e.map(u=>({...u,exportName:"default",policyName:u.handler.name})),gateway:i,next:a}),"policyProcessor")}s(Yo,"createInternalPolicyProcessor");async function Qo({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=er(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=ku(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Qo,"executePolicyProcessor");function Xo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Du,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Hu(l,o)}i=u+1}return n}s(Xo,"parse");function Du(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Du,"decode");function Hu(t,e){try{return e(t)}catch{return t}}s(Hu,"tryDecode");function ei(t,e){try{let n=/v\d+(-\d+)?/g,o=Xo(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(ei,"devPortalBaseURL");var ti="/__zuplo/dev-portal",Uu="dev-portal-id",Nu="dev-portal-host",Mu="zp-account",Zu="zp-project",qu="dev-portal-build",$u=`
|
|
35
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(gu,"reduceToSingleString")});var _o=ze(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.format=void 0;var fu=vo(),hu=Lo(),yu=s((t,...e)=>(0,fu.format)(hu.inspect,t,e),"format");yt.format=yu});var Re=ze(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.debug=pe.withoutEnv=pe.Debugger=void 0;var bu=xo(),wu=_o(),bt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,bu.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,wu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};pe.Debugger=bt;var wt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ko(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(ko,"extract");var Ge;function Ru(t){t||(t=[]),typeof t=="string"&&(t=ko(t)),Ge=new wt(t)}s(Ru,"withoutEnv");pe.withoutEnv=Ru;function Pu(t){let e=globalThis.DEBUG;Ge||(Ge=new wt(ko(e)));let n=new bt(Ge,t);return Ge.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(Pu,"debug");pe.debug=Pu});var Il={};ga(Il,{API_KEY:()=>ii,AWSLoggingPlugin:()=>Qt,AmberfloMeteringInboundPolicy:()=>Ki,AmberfloMeteringPolicy:()=>sn,ApiAuthKeyInboundPolicy:()=>Qi,ApiKeyInboundPolicy:()=>un,AuditLogDataStaxProvider:()=>tn,AuditLogPlugin:()=>nn,Auth0JwtInboundPolicy:()=>Xi,AwsLambdaHandlerExtensions:()=>ki,BasicAuthInboundPolicy:()=>es,BasicRateLimitInboundPolicy:()=>Vr,CachingInboundPolicy:()=>ts,ChangeMethodInboundPolicy:()=>ns,ClearHeadersInboundPolicy:()=>rs,ClearHeadersOutboundPolicy:()=>os,ClerkJwtInboundPolicy:()=>is,CognitoJwtInboundPolicy:()=>ss,CompositeInboundPolicy:()=>as,ConfigurationError:()=>g,ContentTypes:()=>Et,ContextData:()=>le,CreditsMeteringInboundPolicy:()=>us,CryptoBeta:()=>bn,CurityPhantomTokenInboundPolicy:()=>cs,DataDogLoggingPlugin:()=>Mt,DataDogMetricsPlugin:()=>Xt,DynaTraceLoggingPlugin:()=>Wt,DynatraceMetricsPlugin:()=>en,FirebaseJwtInboundPolicy:()=>ls,FormDataToJsonInboundPolicy:()=>ds,GeoFilterInboundPolicy:()=>ps,GoogleCloudLoggingPlugin:()=>Ht,Handler:()=>Vt,HttpProblems:()=>P,HttpStatusCode:()=>vt,JWTScopeValidationInboundPolicy:()=>ms,KeyValueStore:()=>Rn,LoadSubscriptionInboundPolicy:()=>sa,LokiLoggingPlugin:()=>Kt,LookupResult:()=>ke,MemoryZoneReadThroughCache:()=>U,MeteringInboundPolicy:()=>ia,MockApiInboundPolicy:()=>fs,MoesifInboundPolicy:()=>Ps,OktaJwtInboundPolicy:()=>Es,OpenIdJwtInboundPolicy:()=>$,ProblemResponseFormatter:()=>me,PropelAuthJwtInboundPolicy:()=>xs,RateLimitInboundPolicy:()=>Vr,ReadmeMetricsInboundPolicy:()=>Cs,RemoveHeadersInboundPolicy:()=>As,RemoveHeadersOutboundPolicy:()=>Ls,RemoveQueryParamsInboundPolicy:()=>_s,ReplaceStringOutboundPolicy:()=>ks,RequestSizeLimitInboundPolicy:()=>Hs,RequestValidationInboundPolicy:()=>Kr,RequireOriginInboundPolicy:()=>Bs,ResponseSendingEvent:()=>Ce,ResponseSentEvent:()=>Ae,Router:()=>De,SYSTEM_LOGGER:()=>tt,SchemaBasedRequestValidation:()=>Fs,ServiceProviderImpl:()=>hn,SetBodyInboundPolicy:()=>js,SetHeadersInboundPolicy:()=>zs,SetHeadersOutboundPolicy:()=>Vs,SetQueryParamsInboundPolicy:()=>Gs,SetStatusOutboundPolicy:()=>Ws,SleepInboundPolicy:()=>Ks,StripeMeteringPlugin:()=>Mr,StripeWebhookVerificationInboundPolicy:()=>rn,SumoLogicLoggingPlugin:()=>Jt,SupabaseJwtInboundPolicy:()=>Js,SystemLogMap:()=>S,SystemRouteName:()=>oe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ys,UpstreamFirebaseAdminAuthInboundPolicy:()=>Xs,UpstreamFirebaseUserAuthInboundPolicy:()=>ea,UpstreamGcpJwtInboundPolicy:()=>ta,UpstreamGcpServiceAuthInboundPolicy:()=>ra,VMWareLogInsightLoggingPlugin:()=>Yt,ValidateJsonSchemaInbound:()=>oa,ZoneCache:()=>re,ZuploRequest:()=>A,awsLambdaHandler:()=>Di,environment:()=>M,getIdForParameterSchema:()=>gn,getIdForRefSchema:()=>Ns,getIdForRequestBodySchema:()=>fn,getRawOperationDataIdentifierName:()=>Us,httpStatuses:()=>Ot,isRestrictedEnvVariableName:()=>pr,isZuploReadableEnvVariableName:()=>mr,openApiSpecHandler:()=>Hi,originalFetch:()=>He,purgeGatewayCache:()=>Ei,redirectHandler:()=>Ui,sanitizedIdentifierName:()=>be,serialize:()=>It,setMoesifContext:()=>Rs,urlForwardHandler:()=>Ni,urlRewriteHandler:()=>Mi,webSocketHandler:()=>Zi,webSocketPipelineHandler:()=>Fi});module.exports=fa(Il);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},E=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends E{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},pt=class extends E{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new T("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var mt=globalThis,ro=mt.caches;if(ro){let t=ro.open;mt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete mt.caches.default,Object.freeze(mt.caches)}var oo=new Map,En=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Te=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=oo.get(e);r||(r=new En(n),oo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var In="__zuplo-expiry-header",re=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(In);if(!i){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await n.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(In,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(In,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var U=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Te(r),this.#n=new re(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var io="zuplo-request-id",Ve="zp-rid",so="zp-body-removed",Se="cf-ray",xn="cf-ipcity",vn="cf-ipcontinent",On="cf-ipcountry",Tn="cf-iplongitude",Sn="cf-iplatitude",ao="zp-ipcity",uo="zp-ipcontinent",co="zp-ipcountry",lo="zp-iplongitude",po="zp-iplatitude",mo="true-client-ip",Cn="zp-asn",An="zp-asorg",Ln="zp-colo",_n="zp-postalcode",kn="zp-metrocode",Dn="zp-region",Hn="zp-regioncode",Un="zp-timezone",go=[xn,vn,On,Tn,Sn,Cn,An,Ln,_n,kn,Dn,Hn,Un],fo=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];var mi=Oe(Re());var We=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new E("Error in custom 'problemResponseFormat'",{cause:i})}})}},me=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await We.problemResponseFormat(e,n,r)}};function Rt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Rt(n)}return Object.freeze(t)}s(Rt,"deepFreeze");var A=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Rt(this.#e)}get params(){return Rt(this.#t)}user};var Pe=class{static{s(this,"RuntimePlugin")}},ue=class extends Pe{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ke={},ge=[],Do=[],Ho=[],Uo=[];var Pt={addPlugin(t){ge.push(t)},addRequestHook(t){Do.push(t)},addResponseSendingHook(t){Ho.push(t)},addResponseSendingFinalHook(t){Uo.push(t)}},No=s(async(t,e)=>{let n=t;for(let r of Do){let o=await r(n,e);if(o instanceof A)n=o;else{if(o instanceof Response)return o;throw new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Mo=s(async(t,e,n)=>{let r=t;for(let o of Ho){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Zo=s(async(t,e,n)=>{for(let r of Uo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function qo(t=()=>Promise.resolve()){await t(Pt),Ke.value=Pt;for(let e of ge)e instanceof ue&&await e.initialize(Pt);We.setProblemResponseFormat(Pt.problemResponseFormat)}s(qo,"initializeRuntime");var Et={Json:"application/json",Form:"application/x-www-form-urlencoded"};function It(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Et.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Et.Json)||!e?JSON.stringify(t):t}s(It,"serialize");function Je(t){return N.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(N.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(Je,"isSystemRoute");var D=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async R=>{let I=a.pop();return I?I(o,i,n,u):await this.#e(async L=>{let F=await r(L,i);return Eu(F)},n)(R,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(Je(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ce(o,l);i.dispatchEvent(p);let h=B.getContextExtensions(i),m=h.latestRequest,w;try{w=await p.mutableResponse}catch(R){return i.log.error(R),n.errorHandler(o,i,R)}try{w=await h.onResponseSending(w,m,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}try{w=await Mo(w,m,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),n.errorHandler(o,i,R)}i.dispatchEvent(new Ae(o,w));try{await h.onResponseSendingFinal(l,m,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await Zo(l,m,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return w}};function Eu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(It(t),{headers:{"content-type":"application/json"}})}s(Eu,"resultToResponse");var fe=class extends Pe{static{s(this,"MetricsPlugin")}};var S=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new T(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var xt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,S.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=y.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();S.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=Ye.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ye={name:"__system-no-version",pathPrefix:""};var j=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Se)??void 0,c=t.headers.get(mo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new xt(e)),ge.forEach(w=>{if(w instanceof fe){let R=w.getTransport();m.push(R)}}),m.forEach(w=>{w.pushMetrics(h,e)}),a},"metricsProcessor");var oe=(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))(oe||{});var zn=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return P.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&S.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new D({processors:[j],handler:n,gateway:e}),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var vt=(f=>(f[f.CONTINUE=100]="CONTINUE",f[f.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",f[f.PROCESSING=102]="PROCESSING",f[f.EARLY_HINTS=103]="EARLY_HINTS",f[f.OK=200]="OK",f[f.CREATED=201]="CREATED",f[f.ACCEPTED=202]="ACCEPTED",f[f.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",f[f.NO_CONTENT=204]="NO_CONTENT",f[f.RESET_CONTENT=205]="RESET_CONTENT",f[f.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",f[f.MULTI_STATUS=207]="MULTI_STATUS",f[f.ALREADY_REPORTED=208]="ALREADY_REPORTED",f[f.IM_USED=226]="IM_USED",f[f.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",f[f.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",f[f.FOUND=302]="FOUND",f[f.SEE_OTHER=303]="SEE_OTHER",f[f.NOT_MODIFIED=304]="NOT_MODIFIED",f[f.USE_PROXY=305]="USE_PROXY",f[f.SWITCH_PROXY=306]="SWITCH_PROXY",f[f.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",f[f.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",f[f.BAD_REQUEST=400]="BAD_REQUEST",f[f.UNAUTHORIZED=401]="UNAUTHORIZED",f[f.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",f[f.FORBIDDEN=403]="FORBIDDEN",f[f.NOT_FOUND=404]="NOT_FOUND",f[f.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",f[f.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",f[f.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",f[f.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",f[f.CONFLICT=409]="CONFLICT",f[f.GONE=410]="GONE",f[f.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",f[f.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",f[f.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",f[f.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",f[f.URI_TOO_LONG=414]="URI_TOO_LONG",f[f.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",f[f.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",f[f.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",f[f.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",f[f.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",f[f.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",f[f.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",f[f.LOCKED=423]="LOCKED",f[f.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",f[f.TOO_EARLY=425]="TOO_EARLY",f[f.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",f[f.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",f[f.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",f[f.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",f[f.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",f[f.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",f[f.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",f[f.BAD_GATEWAY=502]="BAD_GATEWAY",f[f.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",f[f.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",f[f.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",f[f.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",f[f.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",f[f.LOOP_DETECTED=508]="LOOP_DETECTED",f[f.NOT_EXTENDED=510]="NOT_EXTENDED",f[f.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",f))(vt||{}),$o={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 Iu={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"},Ot=Iu;function xu(t){return`${new URL(t.url).pathname}`}s(xu,"instance");function vu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(Se);return r&&(n.rayId=r),n}s(vu,"trace");var Ou=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:xu(e),trace:vu(e,n),...r},additionalHeaders:o,statusText:Ot[t.status]}),"merge"),Vn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?me.format(e,n,r):me.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:$o[e],...n}}},P=class extends Vn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Ou(this.getProblemFromStatus(e),n,r,o,i);return me.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Tu}=Object.prototype,{propertyIsEnumerable:Su}=Object.prototype;function Gn(t){return Tu.call(t)}s(Gn,"toString");function Q(t){return typeof t=="string"}s(Q,"isString");function Le(t){return Q(t)&&t!==""}s(Le,"isNonEmptyString");function Fo(t){return Gn(t)==="[object RegExp]"}s(Fo,"isRegexp");function Bo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Su.call(t,e))]}s(Bo,"getOwnEnumerableKeys");function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Qe,"isObject");function Wn(t){return typeof t=="number"&&!isNaN(t)}s(Wn,"isNumber");function Kn(t){return t===!0||t===!1}s(Kn,"isBoolean");function jo(t){return typeof t>"u"}s(jo,"isUndefined");function zo(t){return jo(t)||t===null}s(zo,"isUndefinedOrNull");function Xe(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Xe,"isErrorLike");var Vo=new Map;function Go(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Vo.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Vo.set(t,r),r}s(Go,"statusCodesStringToNumberArray");function Ee(t,e,n){if(!e.startsWith("."))throw new g(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new E(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ee,"getValueFromRequestUser");function Jn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new g("Received an array that contains non-string values.");return t}if(Q(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new g(`Expected type of string, received type '${typeof t}'`)}s(Jn,"parseValueToStringArray");function Wo(t){if(t==null)return[];if(!Array.isArray(t))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Qe(n))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Le(n.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Wn(n.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Kn(n.allowCredentials))throw new g("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=Yn(n,"allowedHeaders"),o=Yn(n,"allowedMethods"),i=Yn(n,"exposeHeaders"),a;try{a=Jn(n.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(Wo,"parseCorsPolicies");function Yn(t,e){let n;if(t[e]!==void 0)try{n=Jn(t[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Yn,"parseOptionalProperty");var Tt=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),St=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var Qn=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return P.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=t.lookup(l,c);if(!h)return P.notFound(a,u);let m=h.routeConfiguration,w=Cu(l,d,p,m,n);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&u.log.warn(w.error),P.notFound(a,u))},"optionsHandler"),o=new D({processors:[j],handler:r,gateway:e}),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Cu=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Tt(a.allowedOrigins,n);return u?{isValid:!0,headers:St(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Ko=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new D({processors:[j],handler:n,gateway:e}),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var Xn=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Jo=s((t,e)=>{let n=s(async(o,i)=>{let a=Ke.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return P.notFound(o,i)},"notFoundHandler"),r=new D({processors:[j],handler:n,gateway:e});t.addRoute(Xn,r.execute)},"registerNotMatchedHandler");var Au=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Yo=s(t=>{Au.forEach(e=>t.delete(e))},"stripCorsHeaders"),Ct=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return Yo(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new T(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Lu(o,n.routeData.corsPolicies),u=_u(t,a),c=new Headers(i.headers);return Yo(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Lu=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new g(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),_u=s((t,e)=>{let n=Tt(e.allowedOrigins,t.headers.get("origin"));return n?St(e,n):{}},"getCorsHeaders");var er=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new D({processors:[Ct],handler:n,gateway:e}),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function et(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.name===i);if(!a)throw new g(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new g(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(et,"getInboundPolicyHandlerAndOptions");function ku(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new g(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(ku,"getOutboundPolicyHandlerAndOptions");var tr=s(t=>async(e,n)=>{let r=B.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof A)i=u;else if(u instanceof Request)i=new A(u);else{if(u instanceof Response)return u;throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Du=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r,a.options,a.policyName);if(!(u instanceof Response))throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),At=s(async(t,e,n,r)=>{let o=et(e.route,n.routeData.policies),i=ku(e.route,n.routeData.policies);return Xo({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Qo({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Xo({request:r,context:o,inboundPolicies:t.map(u=>({...u,exportName:"default",policyName:u.handler.name})),outboundPolicies:e.map(u=>({...u,exportName:"default",policyName:u.handler.name})),gateway:i,next:a}),"policyProcessor")}s(Qo,"createInternalPolicyProcessor");async function Xo({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=tr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Du(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(Xo,"executePolicyProcessor");function ei(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Hu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Uu(l,o)}i=u+1}return n}s(ei,"parse");function Hu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Hu,"decode");function Uu(t,e){try{return e(t)}catch{return t}}s(Uu,"tryDecode");function ti(t,e){try{let n=/v\d+(-\d+)?/g,o=ei(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(ti,"devPortalBaseURL");var ni="/__zuplo/dev-portal",Nu="dev-portal-id",Mu="dev-portal-host",Zu="zp-account",qu="zp-project",$u="dev-portal-build",Fu=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -46,20 +46,20 @@
|
|
|
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,n)=>{let r=e.replaceAll(
|
|
51
|
-
`)}s(
|
|
49
|
+
`,ri=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Fu,{headers:{"content-type":"text/html"}});if(!r)return P.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=ti(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:w,body:R}=c;return y.instance.build.ACCOUNT_NAME&&m.set(Zu,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&m.set(qu,y.instance.build.PROJECT_NAME),m.set(Nu,r),m.set(Mu,d.host),m.set($u,y.instance.build.BUILD_ID),await fetch(h.toString(),{headers:m,method:w,body:R,redirect:"manual"})},"devPortalRoute"),a=new D({processors:[j,At],handler:i,gateway:e}),u=new k({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),oi=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(ni.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new D({processors:[j],handler:r,gateway:e}),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ni}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var pi=Oe(Re());var tt="system-logger",ii="api-key";var nr=0,nt=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){nr>=Number.MAX_SAFE_INTEGER&&(nr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:nr++};this.#t[e](u,a)}};var H=class extends Pe{static{s(this,"LogPlugin")}};var Lt=class{static{s(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var rt=class{static{s(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Bu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),ju=new Map(Bu);var zu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],rr=Symbol(".toJSON was called"),Vu=s(t=>{t[rr]=!0;let e=t.toJSON();return delete t[rr],e},"toJSON"),Gu=s(t=>ju.get(t)??Error,"getErrorConstructor"),si=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&Xe(t)){let l=Gu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[rr]!==!0)return Vu(t);let c=s(l=>si({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of zu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Xe(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function z(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?si({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(z,"serializeError");var Wu=/file:\/\/\/(.*?)\/dist\//g,Ku=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Ju="at async Event.respondWith";function ai(t){return typeof t!="string"?t:t.split(`
|
|
50
|
+
`).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(Wu,"").replaceAll(Ku,"").replaceAll(Ju,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
51
|
+
`)}s(ai,"cleanStack");function _t(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
52
52
|
`,newlineOrSpace:`
|
|
53
|
-
`,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=s(m=>{if(u.inlineCharacterLimit===void 0)return m;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")(t,e,n,0)}s(
|
|
56
|
-
`)}s(ai,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function rr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?Vn(t):"unknown"}s(rr,"stringifyNonStringToText");var _t=require("jose");async function Y(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(Y,"fetchRetry");async function ie({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new _t.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ie,"getTokenFromGcpServiceAccount");async function ui(t,e,n){return ci(t,{token:e,returnSecureToken:!0},n)}s(ui,"exchangeFirebaseJwtForIdToken");async function kt(t,e,n){return ci(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(kt,"exchangeGgpJwtForIdToken");async function ci(t,e,n){let r=await Y(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new P({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ci,"fetchToken");var V=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,_t.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Dt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new rt(this.options)}},Ju="https://logging.googleapis.com/v2/entries:write?alt=json",or={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},rt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await V.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:he(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:or[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=_e(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await V.init(this.#e));let n=await ie({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Ju,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var Ht="gcp";function Ut(t){let e={allMessages:he(t.messages)},n="zuplo-production",r=_e(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:or[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Ut,"gcpLogFormat");var ot=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Nt=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new it(this.options)}},ir="__ddtags",sr="__ddattr",ar=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Yu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ar(r)):n.push(`${ar(r)}:${ar(o.toString())}`)}),n.join(",")},"formatTags"),it=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[ir];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[ir]!==void 0);a>-1&&(Object.assign(r,i[a][ir]),i.splice(a,1));let u={},c=n.custom[sr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[sr]!==void 0);l>-1&&(Object.assign(u,i[l][sr]),i.splice(l,1));let d=he(i),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:_e(d),service:e.loggingId,ddtags:Yu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var st=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Qu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:he(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Mt,Zt=class{static{s(this,"RemoteLogTransport")}constructor(e){Mt||(Mt=new C("remote-log-transport",1,Qu(e)))}log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Xu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},li=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:Xu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var ec=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=li(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),qt,$t=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new C("unified-log-transport",1,ec(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var ur=(0,di.debug)("zuplo:logging"),Ft=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(y.instance,e),r=await t.setupUserCoreLogger(y.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;ur("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(et);return i?o.push(new st(i.logger,e.logFormat)):e.isDeno&&o.push(new ot(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new $t({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 tt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){ur("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(et);if(a&&a.captureUserLogs===!0?r.push(new st(a.logger,e.logFormat)):e.isDeno&&r.push(new ot(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new rt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new it({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ge.forEach(u=>{u instanceof U&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new tt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){ur("Gateway.createRequestLoggers");let a=new At(r,o,i),u=new nt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new nt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Ie=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var cr=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},ke=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},lr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},De=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Ie||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new cr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new lr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new ke(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new ke(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var tc=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],se=(0,pi.debug)("zuplo:runtime"),nc=s(t=>{let e=t.findIndex(n=>n.name===Je.name);return e>-1?[...t.splice(e),Je]:[...t,Je]},"setupSystemNoVersion"),G=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;se("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(se("Gateway.initialize"),!t.#e){await Zo(i);let a=await Ft.init(r),u=e(),c={...u,corsPolicies:Go(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){se("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Ct,St,B];#o;setupRoutes=()=>{se("Gateway.setupRoutes");let e=this.routeData,n=nc(e.versions),r=new De(n);if(e.routes.length===0)return zn(r,this),Xn(r,this),Yn(r,this),Wo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ri(r,this),ni(r,this)),zn(r,this),Xn(r,this),Yn(r,this);for(let i of ge)i instanceof ue&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new H({processors:this.#r,handler:a,gateway:this}),c=new Ie(i);r.addRoute(c,u.execute)}),Ko(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 g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return se("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){se("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof P&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=si(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return mo.forEach(r=>{n.delete(r)}),y.instance.isDeno&&go.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ve)??e.headers.get(oo),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let I=new Headers(e.headers);I.set(Ve,r),e=new Request(e,{headers:I})}if(["GET","HEAD"].includes(e.method)&&e.body){let I=new Headers(e.headers);I.set(io,"true"),e=new Request(e,{headers:I,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Bt(e.headers),h=this.#s(e),m=new L(h,{params:d.params}),b=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),E=F.initialize(b,m);if(d.routeConfiguration===Qn&&Ke.value?.notFoundHandler!==void 0){let I=this.#n.lookupByPathOnly(l);E.pathOnlyMatches=I.map(x=>x.routeConfiguration).filter(x=>x instanceof Ie)}try{if(S.addLogger(b,u),!c.pathname.startsWith("/__zuplo")){let D=await Uo(m,b);if(D instanceof Response)return D;{let _=F.getContextExtensions(b);m=D,_.latestRequest=m}}[...tc,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(D=>new RegExp(D).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let x=d.executableHandler;rc(x,d,e),se("Gateway.handleRequest - call user handler");let A=await x(m,b);if(se("Gateway.handleRequest - user handler"),!(A instanceof Response))throw new P(`Invalid Response type from the request handler: ${typeof A}`);if(A.bodyUsed)throw new P("The response object has already been used. Return a new response instead.");if(A.headers.get(Ve)===null&&!A.webSocket){let D=new Headers(A.headers);return D.set(Ve,r),new Response(A.body,{status:A.status,statusText:A.statusText,headers:D,cf:A.cf})}else return A}catch(I){return se("Gateway - error executing handler",I),I instanceof P?(a.error(I),u.warn(I)):u.error(I),await this.#i(m,b,I)}}};function rc(t,e,n){if(se("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(rc,"checkHandler");var mi=s(async(t,e,n)=>{let r=G.instance.routeData.policies,o=Xe([t],r);if(o.length===0)throw new P(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Bt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Sn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(In)??this.#e.get(so)??void 0}get continent(){return this.#e.get(xn)??this.#e.get(ao)??void 0}get country(){return this.#e.get(vn)??this.#e.get(uo)??void 0}get latitude(){return this.#e.get(Tn)??this.#e.get(lo)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(co)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Ln)??void 0}get metroCode(){return this.#e.get(_n)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Hn)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},F=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new P(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},zt=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>mi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{F.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{F.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var oc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function dr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!oc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(dr,"isRestrictedEnvVariableName");function pr(t){return!!t.startsWith("ZUPLO_")}s(pr,"isZuploReadableEnvVariableName");var M=new Proxy({},{get(t,e){if(dr(String(e))&&!pr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var fi=Oe(Re());var X=(0,fi.debug)("zuplo:runtime:external-service");function hi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(hi,"getServiceAuth");async function yi(t){let e=hi();if(!e)throw X("There is no external service auth configured for this zup."),new P("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new P("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=y.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await wi(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new P("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(yi,"externalServiceTunnelConfig");async function bi(t,e){let n=hi();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await wi(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new P("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await He(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new P("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new P("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new P("There are no external services configured for this zup.")}s(bi,"externalServiceHandler");async function wi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=ic(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await gi(`${i}-${o}`),l=await gi(`${i}-${a}-${u}`);return`${c}.${l}`}s(wi,"hashServiceName");async function gi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(gi,"hashSegment");function ic(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var Ri=new Map;Ri.set("service:",bi);var He=globalThis.fetch;globalThis.fetch=function(t,e){let n=sc(e);if(typeof t=="string"){let r=new URL(t),o=Ri.get(r.protocol);return o?o(t,n):He(t,n)}else return He(t,n)};var sc=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Pi=s(()=>{G.purgeGatewayCache()},"purgeGatewayCache"),jt=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await G.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var Ai=Oe(Re());function ac(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(ac,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=ac(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(cc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(K){if(c<n.length&&n[c].type===K)return n[c++].value},"tryConsume"),p=s(function(K){var J=d(K);if(J!==void 0)return J;var xe=n[c],ve=xe.type,Rn=xe.index;throw new TypeError("Unexpected ".concat(ve," at ").concat(Rn,", expected ").concat(K))},"mustConsume"),h=s(function(){for(var K="",J;J=d("CHAR")||d("ESCAPED_CHAR");)K+=J;return K},"consumeText");c<n.length;){var m=d("CHAR"),b=d("NAME"),E=d("PATTERN");if(b||E){var I=m||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:b||u++,prefix:I,suffix:"",pattern:E||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var I=h(),D=d("NAME")||"",_=d("PATTERN")||"",j=h();p("CLOSE"),a.push({name:D||(_?u++:""),pattern:D&&!_?i:_,prefix:I,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function Ei(t,e){return uc(mr(t,e),e)}s(Ei,"compile");function uc(t,e){e===void 0&&(e={});var n=lc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",b=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!b)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<h.length;E++){var I=o(h[E],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var I=o(String(h),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!m){var x=b?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(uc,"tokensToFunction");function cc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(cc,"escapeString");function lc(t){return t&&t.sensitive?"":"i"}s(lc,"flags");var Oi=Oe(Re());var dc=(0,Oi.debug)("zuplo:runtime"),fr=new TextEncoder,Ii={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"},pc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Ue=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new hr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){dc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},hr=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:m,allHeaders:b,singleEncode:E}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let I,x;(!c||!l)&&([I,x]=mc(this.url,this.headers)),this.service=c||I||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let A=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"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>b||!pc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").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=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let w=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=u.inlineCharacterLimit?w:m.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
54
|
+
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Fo(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let m="["+p.newline+a.map((w,R)=>{let I=a.length-1===R?p.newline:","+p.newlineOrSpace,x=i(w,u,c+d,l+1);return u.transform&&(x=u.transform(a,R,x)),p.indent+x+I}).join("")+p.pad+"]";return r.pop(),h(m)}if(Qe(a)){let m=Bo(a);if(u.filter&&(m=m.filter(R=>u.filter?.(a,R))),m.length===0)return"{}";r.push(a);let w="{"+p.newline+m.map((R,I)=>{let x=m.length-1===I?p.newline:","+p.newlineOrSpace,L=typeof R=="symbol",F=!L&&/^[a-z$_][$\w]*$/i.test(R),_=L||F?R:i(R,u,"",l+1),V=i(a[R],u,c+d,l+1);return u.transform&&(V=u.transform(a,R,V)),p.indent+String(_)+": "+V+x}).join("")+p.pad+"}";return r.pop(),h(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
|
|
55
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(_t,"stringifyObject");function he(t){return t.map(e=>z(e))}s(he,"makeErrorsSerializable");function _e(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:ce(z(e))}s(_e,"extractBestMessage");function ui(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Xe(n))if(n.stack)e.push(n.stack);else{let r=_t(z(n));e.push(r)}else if(typeof n=="object"){let r=_t(n);e.push(r)}else{let r=or(n);e.push(r)}}),e.join(`
|
|
56
|
+
`)}s(ui,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function or(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?Gn(t):"unknown"}s(or,"stringifyNonStringToText");var kt=require("jose");async function Y(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(Y,"fetchRetry");async function ie({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new kt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ie,"getTokenFromGcpServiceAccount");async function ci(t,e,n){return li(t,{token:e,returnSecureToken:!0},n)}s(ci,"exchangeFirebaseJwtForIdToken");async function Dt(t,e,n){return li(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Dt,"exchangeGgpJwtForIdToken");async function li(t,e,n){let r=await Y(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new E({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(li,"fetchToken");var G=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,kt.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var Ht=class extends H{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new ot(this.options)}},Yu="https://logging.googleapis.com/v2/entries:write?alt=json",ir={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},ot=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await G.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:he(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:ir[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=_e(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await G.init(this.#e));let n=await ie({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Yu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var Ut="gcp";function Nt(t){let e={allMessages:he(t.messages)},n="zuplo-production",r=_e(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:ir[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Nt,"gcpLogFormat");var it=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===Ut){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nt(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Mt=class extends H{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new st(this.options)}},sr="__ddtags",ar="__ddattr",ur=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Qu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ur(r)):n.push(`${ur(r)}:${ur(o.toString())}`)}),n.join(",")},"formatTags"),st=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[sr]!==void 0);a>-1&&(Object.assign(r,i[a][sr]),i.splice(a,1));let u={},c=n.custom[ar];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[ar]!==void 0);l>-1&&(Object.assign(u,i[l][ar]),i.splice(l,1));let d=he(i),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:_e(d),service:e.loggingId,ddtags:Qu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var at=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===Ut){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nt(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 Xu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:he(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Zt,qt=class{static{s(this,"RemoteLogTransport")}constructor(e){Zt||(Zt=new C("remote-log-transport",1,Xu(e)))}log(e,n){Zt.enqueue(e),n.waitUntil(Zt.waitUntilFlushed())}};var ec={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},di=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:ec[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var tc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=di(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),$t,Ft=class{static{s(this,"UnifiedLogTransport")}constructor(e){$t||($t=new C("unified-log-transport",1,tc(e)))}async log(e,n){$t.enqueue(e),n.waitUntil($t.waitUntilFlushed())}};var cr=(0,pi.debug)("zuplo:logging"),Bt=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(y.instance,e),r=await t.setupUserCoreLogger(y.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;cr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(tt);return i?o.push(new at(i.logger,e.logFormat)):e.isDeno&&o.push(new it(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Ft({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 nt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){cr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(tt);if(a&&a.captureUserLogs===!0?r.push(new at(a.logger,e.logFormat)):e.isDeno&&r.push(new it(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new qt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new ot({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 st({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ge.forEach(u=>{u instanceof H&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new nt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){cr("Gateway.createRequestLoggers");let a=new Lt(r,o,i),u=new rt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new rt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Ie=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var lr=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},ke=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},dr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},De=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Ie||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new lr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new dr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new ke(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new ke(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var se=(0,mi.debug)("zuplo:runtime"),nc=s(t=>{let e=t.findIndex(n=>n.name===Ye.name);return e>-1?[...t.splice(e),Ye]:[...t,Ye]},"setupSystemNoVersion"),N=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;se("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(se("Gateway.initialize"),!t.#e){await qo(i);let a=await Bt.init(r),u=e(),c={...u,corsPolicies:Wo(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){se("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[At,Ct,j];#o;setupRoutes=()=>{se("Gateway.setupRoutes");let e=this.routeData,n=nc(e.versions),r=new De(n);if(e.routes.length===0)return zn(r,this),er(r,this),Qn(r,this),Ko(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(oi(r,this),ri(r,this)),zn(r,this),er(r,this),Qn(r,this);for(let i of ge)i instanceof ue&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new D({processors:this.#r,handler:a,gateway:this}),c=new Ie(i);r.addRoute(c,u.execute)}),Jo(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 g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return se("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){se("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof E&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=ai(i.stack)),o={cause:i}}}return P.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return go.forEach(r=>{n.delete(r)}),y.instance.isDeno&&fo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ve)??e.headers.get(io),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let I=new Headers(e.headers);I.set(Ve,r),e=new Request(e,{headers:I})}if(["GET","HEAD"].includes(e.method)&&e.body){let I=new Headers(e.headers);I.set(so,"true"),e=new Request(e,{headers:I,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new jt(e.headers),h=this.#s(e),m=new A(h,{params:d.params}),w=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),R=B.initialize(w,m);if(d.routeConfiguration===Xn&&Ke.value?.notFoundHandler!==void 0){let I=this.#n.lookupByPathOnly(l);R.pathOnlyMatches=I.map(x=>x.routeConfiguration).filter(x=>x instanceof Ie)}try{if(S.addLogger(w,u),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Je(c):!c.pathname.startsWith("/__zuplo")){let L=await No(m,w);if(L instanceof Response)return L;{let F=B.getContextExtensions(w);m=L,F.latestRequest=m}}Je(c)&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let I=d.executableHandler;rc(I,d,e),se("Gateway.handleRequest - call user handler");let x=await I(m,w);if(se("Gateway.handleRequest - user handler"),!(x instanceof Response))throw new E(`Invalid Response type from the request handler: ${typeof x}`);if(x.bodyUsed)throw new E("The response object has already been used. Return a new response instead.");if(x.headers.get(Ve)===null&&!x.webSocket){let L=new Headers(x.headers);return L.set(Ve,r),new Response(x.body,{status:x.status,statusText:x.statusText,headers:L,cf:x.cf})}else return x}catch(I){return se("Gateway - error executing handler",I),I instanceof E?(a.error(I),u.warn(I)):u.error(I),await this.#i(m,w,I)}}};function rc(t,e,n){if(se("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(rc,"checkHandler");var gi=s(async(t,e,n)=>{let r=N.instance.routeData.policies,o=et([t],r);if(o.length===0)throw new E(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var jt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Cn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(An)??void 0}get city(){return this.#e.get(xn)??this.#e.get(ao)??void 0}get continent(){return this.#e.get(vn)??this.#e.get(uo)??void 0}get country(){return this.#e.get(On)??this.#e.get(co)??void 0}get latitude(){return this.#e.get(Sn)??this.#e.get(po)??void 0}get longitude(){return this.#e.get(Tn)??this.#e.get(lo)??void 0}get colo(){return this.#e.get(Ln)??void 0}get postalCode(){return this.#e.get(_n)??void 0}get metroCode(){return this.#e.get(kn)??void 0}get region(){return this.#e.get(Dn)??void 0}get regionCode(){return this.#e.get(Hn)??void 0}get timezone(){return this.#e.get(Un)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},B=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new E(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},zt=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>gi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{B.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{B.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var oc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function pr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!oc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(pr,"isRestrictedEnvVariableName");function mr(t){return!!t.startsWith("ZUPLO_")}s(mr,"isZuploReadableEnvVariableName");var M=new Proxy({},{get(t,e){if(pr(String(e))&&!mr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var hi=Oe(Re());var X=(0,hi.debug)("zuplo:runtime:external-service");function yi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(yi,"getServiceAuth");async function bi(t){let e=yi();if(!e)throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=y.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await Ri(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(bi,"externalServiceTunnelConfig");async function wi(t,e){let n=yi();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(y.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Ri(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await He(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new E("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}s(wi,"externalServiceHandler");async function Ri(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=ic(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await fi(`${i}-${o}`),l=await fi(`${i}-${a}-${u}`);return`${c}.${l}`}s(Ri,"hashServiceName");async function fi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(fi,"hashSegment");function ic(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ic,"sanitizeEnvironmentType");var Pi=new Map;Pi.set("service:",wi);var He=globalThis.fetch;globalThis.fetch=function(t,e){let n=sc(e);if(typeof t=="string"){let r=new URL(t),o=Pi.get(r.protocol);return o?o(t,n):He(t,n)}else return He(t,n)};var sc=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Ei=s(()=>{N.purgeGatewayCache()},"purgeGatewayCache"),Vt=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await N.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var Li=Oe(Re());function ac(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(ac,"lexer");function gr(t,e){e===void 0&&(e={});for(var n=ac(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(cc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(K){if(c<n.length&&n[c].type===K)return n[c++].value},"tryConsume"),p=s(function(K){var J=d(K);if(J!==void 0)return J;var xe=n[c],ve=xe.type,Pn=xe.index;throw new TypeError("Unexpected ".concat(ve," at ").concat(Pn,", expected ").concat(K))},"mustConsume"),h=s(function(){for(var K="",J;J=d("CHAR")||d("ESCAPED_CHAR");)K+=J;return K},"consumeText");c<n.length;){var m=d("CHAR"),w=d("NAME"),R=d("PATTERN");if(w||R){var I=m||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:w||u++,prefix:I,suffix:"",pattern:R||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var L=d("OPEN");if(L){var I=h(),F=d("NAME")||"",_=d("PATTERN")||"",V=h();p("CLOSE"),a.push({name:F||(_?u++:""),pattern:F&&!_?i:_,prefix:I,suffix:V,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(gr,"parse");function Ii(t,e){return uc(gr(t,e),e)}s(Ii,"compile");function uc(t,e){e===void 0&&(e={});var n=lc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var I=o(h[R],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var I=o(String(h),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!m){var x=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(uc,"tokensToFunction");function cc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(cc,"escapeString");function lc(t){return t&&t.sensitive?"":"i"}s(lc,"flags");var Ti=Oe(Re());var dc=(0,Ti.debug)("zuplo:runtime"),hr=new TextEncoder,xi={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},pc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Ue=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new yr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){dc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},yr=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:m,allHeaders:w,singleEncode:R}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let I,x;(!c||!l)&&([I,x]=mc(this.url,this.headers)),this.service=c||I||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let L=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"),L.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&L.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>w||!pc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
|
|
57
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!L.has("X-Amz-Expires")&&L.set("X-Amz-Expires","86400"),L.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),L.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),L.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Oi(this.encodedPath);let F=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(F.has(_))return!1;F.add(_)}return!0}).map(_=>_.map(V=>Oi(encodeURIComponent(V)))).sort(([_,V],[K,J])=>_<K?-1:_>K?1:V<J?-1:V>J?1:0).map(_=>_.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await ut("AWS4"+this.secretAccessKey,e),i=await ut(o,this.region),a=await ut(i,this.service);r=await ut(a,"aws4_request"),this.cache.set(n,r)}return fr(await ut(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,fr(await vi(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 P("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=gr(await xi(this.body||""))}return e}};async function at(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?fr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,fr.encode(e))}s(at,"hmac");async function xi(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?fr.encode(t):t)}s(xi,"hash");function gr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(gr,"buf2hex");function vi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(vi,"encodeRfc3986");function mc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Ii?[Ii[i],a]:[i,a]}s(mc,"guessServiceRegion");function gc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(gc,"b64ToUint6");function Ti(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=gc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Ti,"base64Decode");function Vt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Vt,"uint6ToB64");function Si(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Vt(o>>>18&63),Vt(o>>>12&63),Vt(o>>>6&63),Vt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Si,"base64Encode");function Ne(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Ne,"numberToString");function fc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Ne(Math.floor(n/60)),i=Ne(n%60);return`${r}${o}${i}`}s(fc,"getCLFOffset");function yr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=Ne(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Ne(t.getHours()),a=Ne(t.getMinutes()),u=Ne(t.getSeconds()),c=fc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(yr,"toCLFDate");var Ci=(0,Ai.debug)("zuplo:runtime"),hc="X-Amzn-Trace-Id",yc="x-amzn-errortype",Li=[],bc=s(async(t,e,n)=>{let r=n;for await(let o of Li)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),W=class extends P{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(hc)??void 0,this.errorType=n.get(yc)??void 0}},_i={addSendingAwsLambdaEventHook:t=>{Li.push(t)}};async function ki(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!i)throw new g("functionName is not set in the handler options");let l=new Ue({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Ci(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,h]=await Ec(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,b;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?b=Pc(t,e):b=await Rc(t,e,{useAwsResourcePathStyle:u}),Ci("Calling onSendingAwsLambdaEvent hook");let E=await bc(t,e,b);E.body=p,E.isBase64Encoded=h;let I=await l.fetch(d,{body:JSON.stringify(E)});try{return wc(I)}catch(x){if(x instanceof W){let A=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&x.traceId?{AMZN_TRACE_ID_HEADER:x.traceId}:void 0;return R.internalServerError(t,e,void 0,A)}throw x}}s(ki,"awsLambdaHandler");async function wc(t){let e;try{e=await t.json()}catch{throw new W("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new W(e.message,t.headers):new W(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new W(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new W(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new W(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new W(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new W("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new W("Response was set to base64 encoded but body was not a string",t.headers);r=Ti(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 W(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(wc,"getResponse");async function Rc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:yr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:xc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Rc,"buildEventVersion1");function Pc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:yr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(Pc,"buildEventVersion2");async function Ec(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Ic(e,o)){let i=await t.arrayBuffer();n=Si(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(Ec,"getBodyResult");function Ic(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Ic,"matchesContentType");function xc(t,e=!1){if(!e)return t;let n=mr(t),r=Ei(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(xc,"getResourcePath");var vc=[502,503,504];async function Me(t,e){if(vc.includes(t.status)){let n=S.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Me,"logBadGatewayResponses");var br;function ye(t){if(br===void 0){let n=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),br=n}return t.log[br]}s(ye,"getHandlerUserLogFunction");async function Di(t,e){let n=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Oc(i);if(!a.isValid)throw new g(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return R.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Me(l,e),l}s(Di,"openApiSpecHandler");var Oc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Hi(t,e){let n=e.route.handler.options;if(!n.location)throw new g("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Hi,"redirectHandler");function Tc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(Tc,"join");async function Ui(t,e){let n=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 g("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=Tc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),h=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),Me(p,e),p}s(Ui,"urlForwardHandler");var Sc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Ni(t,e){let n=ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Sc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Me(d,e),d}s(Ni,"urlRewriteHandler");async function Mi(t,e){let n=y.instance,r=e.route.handler.options,o=ye(e);if(!r||!r.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await yi(u),b=new URL(u);u=new URL(`${m.serviceBaseUrl}${b.pathname}${b.search}`).toString();for(let I in m.tunnelHeaders)p.set(I,m.tunnelHeaders[I])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let h=JSON.stringify({url:u});return new Response(h,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(h)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Mi,"webSocketHandler");var wr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Zi=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function qi(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Zi(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(qi,"wireUpListeners");async function $i(t,e){let n=y.instance,r=e.route.handler.options,o=ye(e);if(!r||!r.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new g("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let x=await l.text(),A=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(A)}let d=new WebSocketPair,[p,h]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let b=l.webSocket;b.accept(),h.accept();let E=r.policies&&r.policies.inbound?wr(r.policies.inbound,"inbound"):[],I=r.policies&&r.policies.outbound?wr(r.policies.outbound,"outbound"):[];return qi(h,b,t,e,E),qi(b,h,t,e,I),new Response(null,{status:101,webSocket:p})}s($i,"webSocketPipelineHandler");var Gt=class extends U{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new C("dyna-trace-log-transport",10,this.#i)};var Wt=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Er(this.options)}},Pr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Cc(t,e){return btoa(`${t}:${e}`)}s(Cc,"createBasicDigest");var Er=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Cc(e.username,e.password),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Pr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new C("loki-log-transport",10,this.#s)};var Kt=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
61
|
-
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new C("sumo-logic-log-transport",10,this.#s)};var Ac="d3a5b78f-8236-48f5-b1df-4fe269d41172",
|
|
62
|
-
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new
|
|
60
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new E("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=fr(await vi(this.body||""))}return e}};async function ut(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?hr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,hr.encode(e))}s(ut,"hmac");async function vi(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?hr.encode(t):t)}s(vi,"hash");function fr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(fr,"buf2hex");function Oi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Oi,"encodeRfc3986");function mc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in xi?[xi[i],a]:[i,a]}s(mc,"guessServiceRegion");function gc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(gc,"b64ToUint6");function Si(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=gc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Si,"base64Decode");function Gt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Gt,"uint6ToB64");function Ci(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(Gt(o>>>18&63),Gt(o>>>12&63),Gt(o>>>6&63),Gt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Ci,"base64Encode");function Ne(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Ne,"numberToString");function fc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Ne(Math.floor(n/60)),i=Ne(n%60);return`${r}${o}${i}`}s(fc,"getCLFOffset");function br(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=Ne(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Ne(t.getHours()),a=Ne(t.getMinutes()),u=Ne(t.getSeconds()),c=fc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(br,"toCLFDate");var Ai=(0,Li.debug)("zuplo:runtime"),hc="X-Amzn-Trace-Id",yc="x-amzn-errortype",_i=[],bc=s(async(t,e,n)=>{let r=n;for await(let o of _i)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),W=class extends E{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(hc)??void 0,this.errorType=n.get(yc)??void 0}},ki={addSendingAwsLambdaEventHook:t=>{_i.push(t)}};async function Di(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!i)throw new g("functionName is not set in the handler options");let l=new Ue({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Ai(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,h]=await Ec(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,w;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?w=Pc(t,e):w=await Rc(t,e,{useAwsResourcePathStyle:u}),Ai("Calling onSendingAwsLambdaEvent hook");let R=await bc(t,e,w);R.body=p,R.isBase64Encoded=h;let I=await l.fetch(d,{body:JSON.stringify(R)});try{return wc(I)}catch(x){if(x instanceof W){let L=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&x.traceId?{AMZN_TRACE_ID_HEADER:x.traceId}:void 0;return P.internalServerError(t,e,void 0,L)}throw x}}s(Di,"awsLambdaHandler");async function wc(t){let e;try{e=await t.json()}catch{throw new W("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new W(e.message,t.headers):new W(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new W(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new W(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new W(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new W(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new W("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new W("Response was set to base64 encoded but body was not a string",t.headers);r=Si(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 W(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(wc,"getResponse");async function Rc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:br(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:xc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Rc,"buildEventVersion1");function Pc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:br(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(Pc,"buildEventVersion2");async function Ec(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Ic(e,o)){let i=await t.arrayBuffer();n=Ci(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(Ec,"getBodyResult");function Ic(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Ic,"matchesContentType");function xc(t,e=!1){if(!e)return t;let n=gr(t),r=Ii(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(xc,"getResourcePath");var vc=[502,503,504];async function Me(t,e){if(vc.includes(t.status)){let n=S.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Me,"logBadGatewayResponses");var wr;function ye(t){if(wr===void 0){let n=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),wr=n}return t.log[wr]}s(ye,"getHandlerUserLogFunction");async function Hi(t,e){let n=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Oc(i);if(!a.isValid)throw new g(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return P.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return Me(l,e),l}s(Hi,"openApiSpecHandler");var Oc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Ui(t,e){let n=e.route.handler.options;if(!n.location)throw new g("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Ui,"redirectHandler");function Tc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(Tc,"join");async function Ni(t,e){let n=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 g("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=Tc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),h=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),Me(p,e),p}s(Ni,"urlForwardHandler");var Sc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Mi(t,e){let n=ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Sc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Me(d,e),d}s(Mi,"urlRewriteHandler");async function Zi(t,e){let n=y.instance,r=e.route.handler.options,o=ye(e);if(!r||!r.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return P.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await bi(u),w=new URL(u);u=new URL(`${m.serviceBaseUrl}${w.pathname}${w.search}`).toString();for(let I in m.tunnelHeaders)p.set(I,m.tunnelHeaders[I])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let h=JSON.stringify({url:u});return new Response(h,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(h)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Zi,"webSocketHandler");var Rr=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),qi=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function $i(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{let u=s(async c=>{let l=await qi(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s($i,"wireUpListeners");async function Fi(t,e){let n=y.instance,r=e.route.handler.options,o=ye(e);if(!r||!r.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return P.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new g("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let x=await l.text(),L=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(L)}let d=new WebSocketPair,[p,h]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let w=l.webSocket;w.accept(),h.accept();let R=r.policies&&r.policies.inbound?Rr(r.policies.inbound,"inbound"):[],I=r.policies&&r.policies.outbound?Rr(r.policies.outbound,"outbound"):[];return $i(h,w,t,e,R),$i(w,h,t,e,I),new Response(null,{status:101,webSocket:p})}s(Fi,"webSocketPipelineHandler");var Wt=class extends H{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Pr(this.options)}},Pr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new C("dyna-trace-log-transport",10,this.#i)};var Kt=class extends H{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Ir(this.options)}},Er=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Cc(t,e){return btoa(`${t}:${e}`)}s(Cc,"createBasicDigest");var Ir=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Cc(e.username,e.password),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Er(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new C("loki-log-transport",10,this.#s)};var Jt=class extends H{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
61
|
+
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new C("sumo-logic-log-transport",10,this.#s)};var Ac="d3a5b78f-8236-48f5-b1df-4fe269d41172",Yt=class extends H{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new vr(this.options)}},vr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=ui(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=or(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${Ac}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new C("vmware-log-insights-log-transport",10,this.#s)};var Qt=class extends H{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Or(this.options)}},Or=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new C("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new Ue({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ce(z(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Tr=new WeakMap,Lc={tags:[]},Xt=class extends fe{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Sr(this.options)}static setContext(n,r){let o=Tr.get(n);o||(o=Lc);let i=Object.assign({...o},r);Tr.set(n,i)}},Sr=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new C("data-dog-metrics-transport",10,this.dispatchFunction,S.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Tr.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Cr(await r.text())}},Cr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Ar=new WeakMap,_c={dimensions:[]},en=class extends fe{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Lr(this.options)}static setContext(n,r){let o=Ar.get(n);o||(o=_c);let i=Object.assign({...o},r);Ar.set(n,i)}},Lr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new C("dynatrace-metrics-transport",10,this.dispatchFunction,S.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Ar.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
|
|
62
|
+
`),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new _r(await r.text())}},_r=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var tn=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var nn=class extends ue{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new kr(e,this.#e,this.#t)}},Bi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),kc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},kr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...kc};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 C("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Bi(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Bi(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(h=>{n.log.error(h)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Dr=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},ae=class extends Dr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Dc="v1",Hc=300;async function ji(t,e,n,r=Hc,o){return await Nc(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(ji,"constructEventAsync");function Uc(t,e){return`${e.timestamp}.${t}`}s(Uc,"makeHMACContent");async function Nc(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Mc(t,e,Dc),l=/\s/.test(n),d=await Fc(Uc(a,u),n);return Zc(a,i,u,d,r,c,l,o)}s(Nc,"verifyHeaderAsync");function Mc(t,e,n){if(!t)throw new ae(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),i=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new ae(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=qc(a,n);if(!u||u.timestamp===-1)throw new ae(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new ae(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Mc,"parseEventDetails");function Zc(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(h=>$c(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
65
|
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw i?new ae(e,t,{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.
|
|
@@ -68,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
68
68
|
`+d}):new ae(e,t,{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)-n.timestamp;if(o>0&&p>o)throw new ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Zc,"validateComputedSignature");function qc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(qc,"parseHeader");function $c(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s($c,"secureCompare");async function Fc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Dr[i[u]];return a.join("")}s(Fc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function Z(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(Z,"optionValidator");var nn=s(async(t,e,n,r)=>{Z(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await Bi(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),R.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");function zi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(zi,"isStripeWebhookEvent");var rn=class extends ue{static{s(this,"MeteringPlugin")}};var Bc={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new P(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new P(i)}}},ji=Bc;async function Hr(t,e,n,r){let o=n.data?.object?.subscription;if(!o)throw new P("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let i=n.data?.object?.client_reference_id,a=n.data?.object?.customer_email;if(!i)throw new P("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new P("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let u=await ji.getSubscription({logger:e.log,stripeSecretKey:r.stripeSecretKey,subscriptionId:o}),c=u.id,l=u.customer,d=u.items?.data.find(E=>E.object==="subscription_item");if(!d||!d.id)throw new P("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new P("Invalid Stripe API result. Expected subscription_item to have a plan.");let h=p.product,m=await zc({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:h,stripeSubscriptionId:c,stripeCustomerId:l,managerEmail:a,managerSub:i,context:e});if(!m)return R.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});let b="routes.oas.json";try{await jc({context:e,stripeProductId:h,stripeSubscriptionId:c,customerKey:m,productKey:b,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:l})}catch(E){return R.internalServerError(t,e,{detail:E.message})}return R.ok(t,e)}s(Hr,"onCheckoutSessionCompleted");async function zc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},h=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await h.json();if(h.status!==200){let b="Error creating API Key Consumer";throw a.log.error(b,m),new P(b)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(zc,"createConsumer");async function jc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!Le(l))throw new T("No Zuplo JWT token set.");let p=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let h="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(h,m),new P(h)}t.log.info("Successfully created/updated metering subscription.",c)}s(jc,"saveSubscription");async function Ur(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!Le(o))throw new T("No Zuplo JWT token set.");let a=n.data.object.id,u=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":e.requestId},method:"GET"});if(!u.ok){let p="Error querying for metering subscription.",h;try{h=await u.json()}catch{h={status:u.status,statusText:u.statusText}}throw e.log.error(p,h),new P(p)}let l=(await u.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return R.ok(t,e,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",h;try{h=await d.json()}catch{h={status:d.status,statusText:d.statusText}}throw e.log.error(p,h),new P(p)}return e.log.info("Successfully canceled metering subscription."),R.ok(t,e)}s(Ur,"onCustomerSubscriptionDeleted");var Nr=class extends rn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)d=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.meteringBucketRegion??"us-central1";if(!Vc(h))throw new g(`StripeMeteringPlugin - The value '${h}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!zi(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"checkout.session.completed":return await Hr(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Ur(c,l,m,{meteringBucketId:d});default:return R.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Yo({inboundPolicies:[{handler:nn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[B,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Gi=new WeakMap,Vi={},on=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Gi.set(e,n)}};async function Wi(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Vo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Gi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new P(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ee(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},h=Vi[n.apiKey];if(!h){let m=n.apiKey,b=t.headers.get("zm-test-id")??"";h=new C("amberflo-ingest-meter",10,async E=>{try{let I=n.url??"https://app.amberflo.io/ingest",x=await fetch(I,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":b}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Vi[m]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),t}s(Wi,"AmberfloMeteringInboundPolicy");async function sn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(sn,"sha256");var Ki=new Map;async function q(t,e){let n,r=Ki.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await sn(JSON.stringify({policyName:t,options:e}))}`,Ki.set(t,n)),n}s(q,"getPolicyCacheName");var Ji="key-metadata-cache-type";function Gc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Gc,"getKeyValue");async function an(t,e,n,r){if(!n.bucketName)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Gc(a,o);if(!u||u==="")return i("No key present");let c=await Wc(u),l=await q(r,o),d=new N(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ji&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},m=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(h)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),x=JSON.parse(I);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new P(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let b=await m.json(),E={isValid:!0,typeId:Ji,user:{sub:b.name,data:b.metadata}};return t.user=E.user,d.put(c,E,o.cacheTtlSeconds),t}s(an,"ApiKeyInboundPolicy");async function Wc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Wc,"hashValue");var Yi=an;var ut=require("jose");var Mr={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Mr[e.jwkUrl]||(Mr[e.jwkUrl]=(0,ut.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ut.jwtVerify)(t,Mr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ut.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),$=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(h=>R.unauthorized(t,e,{detail:h}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,n)}catch(m){let b=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${b.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Qi=s(async(t,e,n,r)=>$(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Xi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>R.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),m=d.substring(p+1),b=n.accounts.find(E=>E.username===h&&E.password===m);return b||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Yc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Qc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Qc,"digestMessage");var Xc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Qc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function es(t,e,n,r){let o=await q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Xc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let h=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Yc.forEach(b=>m.headers.delete(b)),m.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(es,"CachingInboundPolicy");var ts=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var ns=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new L(t,{headers:o})},"ClearHeadersInboundPolicy");var rs=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var os=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",$(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var is=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return $(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ss=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Xe(n.policies,o?.routeData.policies);return er(i)(t,e)},"CompositeInboundPolicy");var as=s(async(t,e,n)=>{let r=t.user;if(!r)return R.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return R.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await el(i,o,e);if(!a)return R.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return R.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return R.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await tl(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function el(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(el,"getSubscription");async function tl(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(tl,"consumeSubscription");var us=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return R.unauthorized(t,e,{detail:"No authorization header"});let i=nl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await q(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),R.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):R.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function nl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(nl,"getToken");var cs=s(async(t,e,n,r)=>(Z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),$(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ls=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new L(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ze="__unknown__",ds=s(async(t,e,n,r)=>{let o={allow:{countries:$e(n.allow?.countries,"allow.countries",r),regionCodes:$e(n.allow?.regionCodes,"allow.regionCode",r),asns:$e(n.allow?.asns,"allow.asOrganization",r)},block:{countries:$e(n.block?.countries,"block.countries",r),regionCodes:$e(n.block?.regionCodes,"block.regionCode",r),asns:$e(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ze,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ze,u=e.incomingRequestProperties.asn?.toString()??Ze,c=o.ignoreUnknown&&i===Ze,l=o.ignoreUnknown&&a===Ze,d=o.ignoreUnknown&&u===Ze,p=o.allow.countries,h=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return qe(t,e,r,i,a,u);let b=o.block.countries,E=o.block.regionCodes,I=o.block.asns;return b.length>0&&b.includes(i)&&!c||E.length>0&&E.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?qe(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function qe(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),R.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(qe,"blockedResponse");function $e(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s($e,"toLowerStringArray");var ps=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var gs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Zr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Zr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ms(a[u])}else return a.length>0?ms(a[0]):Zr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ms(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(ms,"generateResponse");var Zr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return R.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var rl="Incoming",ol={logRequestBody:!0,logResponseBody:!0};function fs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(fs,"headersToObject");function hs(){return new Date().toISOString()}s(hs,"timestamp");var qr=new WeakMap,il={};function ws(t,e){let n=qr.get(t);n||(n=il);let r=Object.assign({...n},e);qr.set(t,r)}s(ws,"setMoesifContext");async function ys(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(ys,"readBody");var sl={},$r;function bs(){if(!$r)throw new P("Invalid State - no _lastLogger");return $r}s(bs,"getLastLogger");function al(t){let e=sl[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);bs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||bs().error({status:o.status,body:await o.text()})})),e}s(al,"getDispatcher");async function Rs(t,e,n,r){$r=e.log;let o=hs(),i=Object.assign(ol,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ys(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=al(i.applicationId),d=t.headers.get("true-client-ip"),p=qr.get(e)??{},h={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:fs(t.headers)},m=i.logResponseBody?await ys(u,e):void 0,b={time:hs(),status:u.status,headers:fs(u.headers),body:m},E={request:h,response:b,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:rl};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),t}s(Rs,"MoesifInboundPolicy");var Ps=s(async(t,e,n,r)=>$(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Es=require("jose");var Fr,Is=s(async(t,e,n,r)=>{if(!Fr)try{Fr=await(0,Es.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return $(t,e,{issuer:n.authUrl,secret:Fr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var vs=Oe(Re());var un=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Br=class extends un{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},zr=class extends un{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function ul(t,e){if(zo(t))throw new Br(e)}s(ul,"throwIfUndefinedOrNull");function ct(t,e){if(ul(t,e),!Q(t))throw new zr(e,"string")}s(ct,"throwIfNotString");var cn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ct(e,"redisClientUrl"),ct(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ct(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ct(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var dn=(0,vs.debug)("zuplo:policies:RateLimitInboundPolicy"),cl="strict",ll=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),dl=s(async t=>({key:`ip-${ll(t)}`}),"getIP"),pl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),ml=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pn;function gl(t,e){let n;if(pn)return pn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new ln,pn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=cn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return pn=n,n}s(gl,"getRedisClient");async function xs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(xs,"getCountAndUpdateExpiry");function fl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new P(c)}return u},"outerFunction")}s(fl,"wrapUserFunction");var hl="Retry-After",jr=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[hl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:fl(n,r),user:pl,ip:dl,all:ml}[n.rateLimitBy],d=await l(t,e,r),p=d.key,h=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",E=gl(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??cl)==="async"){let _=await q(r,n),j=new re(_,{logger:S.getLogger(e)}),K=xs(x,m,E,i,e.requestId),J=await j.get(x);if(J!==void 0&&J<=Date.now()){dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let xe=Math.round((J-Date.now())/1e3);return u(b,xe)}return e.addEventListener("responseSending",xe=>{try{let ve=xe,Rn=ve.mutableResponse;ve.mutableResponse=(async()=>{let lt=await K;if(lt.count>h){let sa=Date.now()+lt.ttlSeconds*1e3,aa=j.put(x,sa,lt.ttlSeconds).catch(eo=>{throw i.error(new T("Error caching rate limit result.",{cause:eo})),eo});return e.waitUntil(aa),dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(b,lt.ttlSeconds)}return Rn})()}catch(ve){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,ve)}}),t}let D=await xs(x,m,E,i,e.requestId);return D.count>h?(dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(b,D.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Vr;function Os(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Os,"headersToNameValuePairs");function yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(yl,"queryToNameValueParis");function bl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(bl,"parseIntOrUndefined");var Ts={};async function Ss(t,e,n,r){let o=new Date,i=Date.now();return Vr||(Vr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ee(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ee(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Vr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Os(t.headers),queryString:yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Os(a.headers),content:{size:bl(t.headers.get("content-length"))}}}]}}},d=Ts[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async h=>{try{let m=n.url??"https://metrics.readme.io/request",b=await fetch(m,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});b.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${b.status}: '${await b.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Ts[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Ss,"ReadmeMetricsInboundPolicy");var Cs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var As=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Ls=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var _s=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ks=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ds=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ks():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ks():t},"RequestSizeLimitInboundPolicy");function Hs(t,e,n){return`_${be(t+"_"+e+"_"+n)}`}s(Hs,"getRawOperationDataIdentifierName");function mn(t,e,n,r){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(mn,"getIdForParameterSchema");function gn(t,e,n){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${be(n.toLowerCase())}`}s(gn,"getIdForRequestBodySchema");function Us(t,e){return`_${be(t)}__${be(e)}`}s(Us,"getIdForRefSchema");function be(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(be,"sanitizedIdentifierName");var Fe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Be=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=mn(n,r,o,c.name),p=G.instance.schemaValidator[d],h=p(e[c.name]),m=Gr(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Gr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ns(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let b=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=R.badRequest(e,t,{detail:`${b}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",b,[r],m),ne(n.validateBody))return E}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,b=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?b:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=gn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?b:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Gr(l),h=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return h}s(Ns,"handleBodyValidation");function Ms(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Fe(t),i=Be(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=R.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Ms,"handleHeadersValidation");function Zs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(Zs,"handlePathParameterValidation");function qs(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s(qs,"handleQueryParameterValidation");var Wr=s(async(t,e,n)=>{let r=qs(e,t,n);if(r!==void 0||(r=Zs(e,t,n),r!==void 0)||(r=Ms(e,t,n),r!==void 0))return r;let o=await Ns(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),$s=Wr;var Fs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return R.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Bs=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var js=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Vs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var Gs=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var wl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ws=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wl(n.sleepInMs),t},"SleepInboundPolicy");var Ks=s(async(t,e,n,r)=>{Z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await $(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof L))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new P(`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?R.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Js=s(async(t,e,n,r)=>{Z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await q(r,n),i=new N(o,e),a=await i.get(r);if(!a){let u=await Rl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Rl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Y({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new P("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 P("Response returned from Azure AD is not in the expected format.")}s(Rl,"getAccessToken");var Ys="https://accounts.google.com/o/oauth2/token",Kr,Qs=s(async(t,e,n,r)=>{Z(n,r).required("serviceAccountJson","string"),Kr||(Kr=await V.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await q(r,n),a=new N(i,e),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Kr,audience:Ys,payload:o}),l=await kt(Ys,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new P("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",El=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Jr,Xs=s(async(t,e,n,r)=>{if(Z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(El.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Jr||(Jr=await V.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new P("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new P(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ee(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new P(`Unable to determine user from for the policy ${r}`);let a=await q(r,n),u=new N(a,e),c={uid:i,claims:o},l=await sn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Jr,audience:Pl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await ui(h,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new P("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Yr,ea=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string"),Yr||(Yr=await V.init(n.serviceAccountJson));let o=await ie({serviceAccount:Yr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var ta="https://www.googleapis.com/oauth2/v4/token",Qr,na=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qr||(Qr=await V.init(n.serviceAccountJson));let o=await q(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new N(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Qr,audience:ta,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await kt(ta,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new P("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ra=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return R.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("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 R.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var oa=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,h)=>{let m=le.get(h,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:E,meteringServiceUrl:I}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${I}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${E}`,"zp-rid":h.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=le.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ia=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let h=`${n.bucketId}-${l}`,m=new re(h,{logger:S.getLogger(e)}),b=await m.get(h);if(b)d=b;else{let E=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!E.ok)return e.log.error(await E.text()),R.forbidden(t,e);d=await E.json(),m.put(h,d,15).catch(I=>{throw o.error(I),I})}}catch(h){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,h)}if((!d||!d.data||d.data.length===0)&&!i)return R.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return le.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var fn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Xr=["sha-1","sha-256","sha-384","sha-512"],hn=class{static{s(this,"BaseCryptoBeta")}};var yn=class extends hn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Xr.includes(e.toLowerCase()))throw new P(`Algorithm ${e} is not supported. Try using ${Xr.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wn=class extends bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new dt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
71
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Zc,"validateComputedSignature");function qc(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(qc,"parseHeader");function $c(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s($c,"secureCompare");async function Fc(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Hr[i[u]];return a.join("")}s(Fc,"computeHMACSignatureAsync");var Hr=new Array(256);for(let t=0;t<Hr.length;t++)Hr[t]=t.toString(16).padStart(2,"0");function Z(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(Z,"optionValidator");var rn=s(async(t,e,n,r)=>{Z(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await ji(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),P.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");function zi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(zi,"isStripeWebhookEvent");var on=class extends ue{static{s(this,"MeteringPlugin")}};var Bc={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new E(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new E(i)}}},Vi=Bc;async function Ur(t,e,n,r){let o=n.data?.object?.subscription;if(!o)throw new E("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let i=n.data?.object?.client_reference_id,a=n.data?.object?.customer_email;if(!i)throw new E("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new E("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let u=await Vi.getSubscription({logger:e.log,stripeSecretKey:r.stripeSecretKey,subscriptionId:o}),c=u.id,l=u.customer,d=u.items?.data.find(R=>R.object==="subscription_item");if(!d||!d.id)throw new E("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new E("Invalid Stripe API result. Expected subscription_item to have a plan.");let h=p.product,m=await jc({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:h,stripeSubscriptionId:c,stripeCustomerId:l,managerEmail:a,managerSub:i,context:e});if(!m)return P.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});let w="routes.oas.json";try{await zc({context:e,stripeProductId:h,stripeSubscriptionId:c,customerKey:m,productKey:w,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:l})}catch(R){return P.internalServerError(t,e,{detail:R.message})}return P.ok(t,e)}s(Ur,"onCheckoutSessionCompleted");async function jc({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${t}/consumers`,c);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},h=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await h.json();if(h.status!==200){let w="Error creating API Key Consumer";throw a.log.error(w,m),new E(w)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:e,stripeProductId:n}),d}s(jc,"createConsumer");async function zc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a,customerExternalId:u}){let c={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,productKey:o,customerExternalId:u},{authApiJWT:l,meteringServiceUrl:d}=y.instance;if(!Le(l))throw new T("No Zuplo JWT token set.");let p=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let h="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(h,m),new E(h)}t.log.info("Successfully created/updated metering subscription.",c)}s(zc,"saveSubscription");async function Nr(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!Le(o))throw new T("No Zuplo JWT token set.");let a=n.data.object.id,u=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":e.requestId},method:"GET"});if(!u.ok){let p="Error querying for metering subscription.",h;try{h=await u.json()}catch{h={status:u.status,statusText:u.statusText}}throw e.log.error(p,h),new E(p)}let l=(await u.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return P.ok(t,e,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${i}/internal/v1/metering/${r.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",h;try{h=await d.json()}catch{h={status:d.status,statusText:d.statusText}}throw e.log.error(p,h),new E(p)}return e.log.info("Successfully canceled metering subscription."),P.ok(t,e)}s(Nr,"onCustomerSubscriptionDeleted");var Mr=class extends on{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)d=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.meteringBucketRegion??"us-central1";if(!Vc(h))throw new g(`StripeMeteringPlugin - The value '${h}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!zi(m))return P.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"checkout.session.completed":return await Ur(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Nr(c,l,m,{meteringBucketId:d});default:return P.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=Qo({inboundPolicies:[{handler:rn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new D({processors:[j,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Vc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(Vc,"isMetricsRegion");var Wi=new WeakMap,Gi={},sn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){Wi.set(e,n)}};async function Ki(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Go(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Wi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new E(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ee(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},h=Gi[n.apiKey];if(!h){let m=n.apiKey,w=t.headers.get("zm-test-id")??"";h=new C("amberflo-ingest-meter",10,async R=>{try{let I=n.url??"https://app.amberflo.io/ingest",x=await fetch(I,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Gi[m]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),t}s(Ki,"AmberfloMeteringInboundPolicy");async function an(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(an,"sha256");var Ji=new Map;async function q(t,e){let n,r=Ji.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await an(JSON.stringify({policyName:t,options:e}))}`,Ji.set(t,n)),n}s(q,"getPolicyCacheName");var Yi="key-metadata-cache-type";function Gc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Gc,"getKeyValue");async function un(t,e,n,r){if(!n.bucketName)if(M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=M.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(I=>o.allowUnauthenticatedRequests?t:P.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=Gc(a,o);if(!u||u==="")return i("No key present");let c=await Wc(u),l=await q(r,o),d=new U(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Yi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},m=await Y({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(h)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let I=await m.text(),x=JSON.parse(I);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new E(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let w=await m.json(),R={isValid:!0,typeId:Yi,user:{sub:w.name,data:w.metadata}};return t.user=R.user,d.put(c,R,o.cacheTtlSeconds),t}s(un,"ApiKeyInboundPolicy");async function Wc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Wc,"hashValue");var Qi=un;var ct=require("jose");var Zr={},Kc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Zr[e.jwkUrl]||(Zr[e.jwkUrl]=(0,ct.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ct.jwtVerify)(t,Zr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Jc=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ct.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),$=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(h=>P.unauthorized(t,e,{detail:h}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Kc:Jc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,n)}catch(m){let w=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Xi=s(async(t,e,n,r)=>$(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var es=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>P.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),m=d.substring(p+1),w=n.accounts.find(R=>R.username===h&&R.password===m);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Yc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Qc(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Qc,"digestMessage");var Xc=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Qc(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function ts(t,e,n,r){let o=await q(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Xc(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let h=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Yc.forEach(w=>m.headers.delete(w)),m.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(ts,"CachingInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new A(t,{method:n.method})},"ChangeMethodInboundPolicy");var rs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new A(t,{headers:o})},"ClearHeadersInboundPolicy");var os=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var is=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",$(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ss=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return $(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var as=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=N.instance,i=et(n.policies,o?.routeData.policies);return tr(i)(t,e)},"CompositeInboundPolicy");var us=s(async(t,e,n)=>{let r=t.user;if(!r)return P.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return P.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await el(i,o,e);if(!a)return P.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return P.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return P.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await tl(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function el(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(el,"getSubscription");async function tl(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(tl,"consumeSubscription");var cs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return P.unauthorized(t,e,{detail:"No authorization header"});let i=nl(o);if(!i)return P.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await q(r,n),u=new U(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),P.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):P.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function nl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(nl,"getToken");var ls=s(async(t,e,n,r)=>(Z(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),$(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ds=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new A(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ze="__unknown__",ps=s(async(t,e,n,r)=>{let o={allow:{countries:$e(n.allow?.countries,"allow.countries",r),regionCodes:$e(n.allow?.regionCodes,"allow.regionCode",r),asns:$e(n.allow?.asns,"allow.asOrganization",r)},block:{countries:$e(n.block?.countries,"block.countries",r),regionCodes:$e(n.block?.regionCodes,"block.regionCode",r),asns:$e(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ze,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ze,u=e.incomingRequestProperties.asn?.toString()??Ze,c=o.ignoreUnknown&&i===Ze,l=o.ignoreUnknown&&a===Ze,d=o.ignoreUnknown&&u===Ze,p=o.allow.countries,h=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return qe(t,e,r,i,a,u);let w=o.block.countries,R=o.block.regionCodes,I=o.block.asns;return w.length>0&&w.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||I.length>0&&I.includes(u)&&!d?qe(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function qe(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),P.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(qe,"blockedResponse");function $e(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s($e,"toLowerStringArray");var ms=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var fs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return qr(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return qr(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return gs(a[u])}else return a.length>0?gs(a[0]):qr(r,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function gs(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(gs,"generateResponse");var qr=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return P.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var rl="Incoming",ol={logRequestBody:!0,logResponseBody:!0};function hs(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(hs,"headersToObject");function ys(){return new Date().toISOString()}s(ys,"timestamp");var $r=new WeakMap,il={};function Rs(t,e){let n=$r.get(t);n||(n=il);let r=Object.assign({...n},e);$r.set(t,r)}s(Rs,"setMoesifContext");async function bs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(bs,"readBody");var sl={},Fr;function ws(){if(!Fr)throw new E("Invalid State - no _lastLogger");return Fr}s(ws,"getLastLogger");function al(t){let e=sl[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ws().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ws().error({status:o.status,body:await o.text()})})),e}s(al,"getDispatcher");async function Ps(t,e,n,r){Fr=e.log;let o=ys(),i=Object.assign(ol,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await bs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=al(i.applicationId),d=t.headers.get("true-client-ip"),p=$r.get(e)??{},h={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:hs(t.headers)},m=i.logResponseBody?await bs(u,e):void 0,w={time:ys(),status:u.status,headers:hs(u.headers),body:m},R={request:h,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:rl};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),t}s(Ps,"MoesifInboundPolicy");var Es=s(async(t,e,n,r)=>$(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Is=require("jose");var Br,xs=s(async(t,e,n,r)=>{if(!Br)try{Br=await(0,Is.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return $(t,e,{issuer:n.authUrl,secret:Br,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Os=Oe(Re());var cn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},jr=class extends cn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},zr=class extends cn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function ul(t,e){if(zo(t))throw new jr(e)}s(ul,"throwIfUndefinedOrNull");function lt(t,e){if(ul(t,e),!Q(t))throw new zr(e,"string")}s(lt,"throwIfNotString");var ln=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return lt(e,"redisClientUrl"),lt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){lt(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},dn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(lt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var pn=(0,Os.debug)("zuplo:policies:RateLimitInboundPolicy"),cl="strict",ll=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),dl=s(async t=>({key:`ip-${ll(t)}`}),"getIP"),pl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),ml=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),mn;function gl(t,e){let n;if(mn)return mn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new dn,mn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!Q(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=ln.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return mn=n,n}s(gl,"getRedisClient");async function vs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(vs,"getCountAndUpdateExpiry");function fl(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new E(c)}return u},"outerFunction")}s(fl,"wrapUserFunction");var hl="Retry-After",Vr=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[hl]=l.toString()),P.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:fl(n,r),user:pl,ip:dl,all:ml}[n.rateLimitBy],d=await l(t,e,r),p=d.key,h=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",R=gl(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??cl)==="async"){let _=await q(r,n),V=new re(_,{logger:S.getLogger(e)}),K=vs(x,m,R,i,e.requestId),J=await V.get(x);if(J!==void 0&&J<=Date.now()){pn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let xe=Math.round((J-Date.now())/1e3);return u(w,xe)}return e.addEventListener("responseSending",xe=>{try{let ve=xe,Pn=ve.mutableResponse;ve.mutableResponse=(async()=>{let dt=await K;if(dt.count>h){let aa=Date.now()+dt.ttlSeconds*1e3,ua=V.put(x,aa,dt.ttlSeconds).catch(to=>{throw i.error(new T("Error caching rate limit result.",{cause:to})),to});return e.waitUntil(ua),pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,dt.ttlSeconds)}return Pn})()}catch(ve){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,ve)}}),t}let F=await vs(x,m,R,i,e.requestId);return F.count>h?(pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,F.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;pn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var Gr;function Ts(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ts,"headersToNameValuePairs");function yl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(yl,"queryToNameValueParis");function bl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(bl,"parseIntOrUndefined");var Ss={};async function Cs(t,e,n,r){let o=new Date,i=Date.now();return Gr||(Gr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ee(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ee(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Gr,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ts(t.headers),queryString:yl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ts(a.headers),content:{size:bl(t.headers.get("content-length"))}}}]}}},d=Ss[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async h=>{try{let m=n.url??"https://metrics.readme.io/request",w=await fetch(m,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Ss[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Cs,"ReadmeMetricsInboundPolicy");var As=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new A(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ls=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var _s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new A(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ks=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Ds=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Hs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Ds():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ds():t},"RequestSizeLimitInboundPolicy");function Us(t,e,n){return`_${be(t+"_"+e+"_"+n)}`}s(Us,"getRawOperationDataIdentifierName");function gn(t,e,n,r){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(gn,"getIdForParameterSchema");function fn(t,e,n){return`_${be(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${be(n.toLowerCase())}`}s(fn,"getIdForRequestBodySchema");function Ns(t,e){return`_${be(t)}__${be(e)}`}s(Ns,"getIdForRefSchema");function be(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(be,"sanitizedIdentifierName");var Fe=s(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Be=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=gn(n,r,o,c.name),p=N.instance.schemaValidator[d],h=p(e[c.name]),m=Wr(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Wr=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Ms(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=P.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",w,[r],m),ne(n.validateBody))return R}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=fn(t.route.path,e.method,o),u=N.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=P.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Wr(l),h=P.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return h}s(Ms,"handleBodyValidation");function Zs(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Fe(t),i=Be(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=P.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(Zs,"handleHeadersValidation");function qs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(qs,"handlePathParameterValidation");function $s(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Fe(t),o=Be(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=P.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s($s,"handleQueryParameterValidation");var Kr=s(async(t,e,n)=>{let r=$s(e,t,n);if(r!==void 0||(r=qs(e,t,n),r!==void 0)||(r=Zs(e,t,n),r!==void 0))return r;let o=await Ms(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Fs=Kr;var Bs=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return P.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var js=s(async(t,e,n)=>new A(t,{body:n.body}),"SetBodyInboundPolicy");var zs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new A(t,{headers:i})},"SetHeadersInboundPolicy");var Vs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Gs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new A(i.toString(),t)},"SetQueryParamsInboundPolicy");var Ws=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var wl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Ks=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wl(n.sleepInMs),t},"SleepInboundPolicy");var Js=s(async(t,e,n,r)=>{Z(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await $(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof A))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new E(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?P.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Ys=s(async(t,e,n,r)=>{Z(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await q(r,n),i=new U(o,e),a=await i.get(r);if(!a){let u=await Rl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Rl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Y({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new E("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new E("Response returned from Azure AD is not in the expected format.")}s(Rl,"getAccessToken");var Qs="https://accounts.google.com/o/oauth2/token",Jr,Xs=s(async(t,e,n,r)=>{Z(n,r).required("serviceAccountJson","string"),Jr||(Jr=await G.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await q(r,n),a=new U(i,e),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Jr,audience:Qs,payload:o}),l=await Dt(Qs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new E("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",El=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Yr,ea=s(async(t,e,n,r)=>{if(Z(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(El.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Yr||(Yr=await G.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new E("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new E(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ee(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new E(`Unable to determine user from for the policy ${r}`);let a=await q(r,n),u=new U(a,e),c={uid:i,claims:o},l=await an(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Yr,audience:Pl,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await ci(h,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new E("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Qr,ta=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string"),Qr||(Qr=await G.init(n.serviceAccountJson));let o=await ie({serviceAccount:Qr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var na="https://www.googleapis.com/oauth2/v4/token",Xr,ra=s(async(t,e,n,r)=>{Z(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Xr||(Xr=await G.init(n.serviceAccountJson));let o=await q(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new U(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Xr,audience:na,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await Dt(na,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new E("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var oa=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return P.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("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 P.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(d,p,h)=>{let m=le.get(h,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:R,meteringServiceUrl:I}=y.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${I}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${R}`,"zp-rid":h.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){h.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=le.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return P.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var sa=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:P.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(M.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=M.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=y.instance,{sub:l}=a,d;try{let h=`${n.bucketId}-${l}`,m=new re(h,{logger:S.getLogger(e)}),w=await m.get(h);if(w)d=w;else{let R=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"});if(!R.ok)return e.log.error(await R.text()),P.forbidden(t,e);d=await R.json(),m.put(h,d,15).catch(I=>{throw o.error(I),I})}}catch(h){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,h)}if((!d||!d.data||d.data.length===0)&&!i)return P.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&i)return t;let p=d&&d.data?d.data[0]:void 0;return le.set(e,"subscription",p),t},"LoadSubscriptionInboundPolicy");var hn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var eo=["sha-1","sha-256","sha-384","sha-512"],yn=class{static{s(this,"BaseCryptoBeta")}};var bn=class extends yn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!eo.includes(e.toLowerCase()))throw new E(`Algorithm ${e} is not supported. Try using ${eo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var wn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Rn=class extends wn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new pt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
|
|
72
72
|
/*! For license information please see index.minified.js.LEGAL.txt */
|