@zuplo/runtime 5.1805.0 → 5.1807.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 +2 -6
- package/index.minified.js +2 -2
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -2542,6 +2542,8 @@ export declare interface MoesifInboundPolicyOptions {
|
|
|
2542
2542
|
logResponseBody?: boolean;
|
|
2543
2543
|
}
|
|
2544
2544
|
|
|
2545
|
+
/* Excluded from this release type: MonetizationInboundPolicy */
|
|
2546
|
+
|
|
2545
2547
|
/**
|
|
2546
2548
|
* The options for this policy.
|
|
2547
2549
|
*/
|
|
@@ -2578,12 +2580,6 @@ export declare interface MonetizationInboundPolicyOptions {
|
|
|
2578
2580
|
meterOnStatusCodes?: string | number[];
|
|
2579
2581
|
}
|
|
2580
2582
|
|
|
2581
|
-
export declare class MonetizationPolicy extends InboundPolicy<MonetizationInboundPolicyOptions> {
|
|
2582
|
-
static getSubscription(context: ZuploContext): StoredMeteringSubscriptionWithQuotas | undefined;
|
|
2583
|
-
static setMeters(context: ZuploContext, meters: MonetizationPolicyMeters): void;
|
|
2584
|
-
handler(request: ZuploRequest<RequestGeneric>, context: ZuploContext): Promise<ZuploRequest<RequestGeneric> | Response>;
|
|
2585
|
-
}
|
|
2586
|
-
|
|
2587
2583
|
declare type MonetizationPolicyMeters = {
|
|
2588
2584
|
[Key in string]: number;
|
|
2589
2585
|
};
|
package/index.minified.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
`))):u=t.stylize("[Circular]","special")),jo(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(er,"formatProperty");function ku(t,e){if(jo(e))return t.stylize("undefined","undefined");if(zo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Au(e))return t.stylize(""+e,"number");if(Ou(e))return t.stylize(""+e,"boolean");if(Go(e))return t.stylize("null","null")}s(ku,"formatPrimitive");function Du(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(Du,"reduceToSingleString")});var Ko=Je(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.format=void 0;var Mu=Fo(),Uu=Wo(),Hu=s((t,...e)=>(0,Mu.format)(Uu.inspect,t,e),"format");vt.format=Hu});var Pe=Je(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.debug=me.withoutEnv=me.Debugger=void 0;var Nu=$o(),Zu=Ko(),St=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Nu.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,Zu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};me.Debugger=St;var Tt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Jo(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Jo,"extract");var Xe;function qu(t){t||(t=[]),typeof t=="string"&&(t=Jo(t)),Xe=new Tt(t)}s(qu,"withoutEnv");me.withoutEnv=qu;function $u(t){let e=globalThis.DEBUG;Xe||(Xe=new Tt(Jo(e)));let n=new St(Xe,t);return Xe.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s($u,"debug");me.debug=$u});var ql={};Da(ql,{API_KEY:()=>Pi,AWSLoggingPlugin:()=>cn,AmberfloMeteringInboundPolicy:()=>fs,AmberfloMeteringPolicy:()=>hn,ApiAuthKeyInboundPolicy:()=>bs,ApiKeyInboundPolicy:()=>bn,AuditLogDataStaxProvider:()=>pn,AuditLogPlugin:()=>mn,Auth0JwtInboundPolicy:()=>ws,AwsLambdaHandlerExtensions:()=>Ki,BasicAuthInboundPolicy:()=>Rs,BasicRateLimitInboundPolicy:()=>co,CachingInboundPolicy:()=>Ps,ChangeMethodInboundPolicy:()=>Is,ClearHeadersInboundPolicy:()=>Es,ClearHeadersOutboundPolicy:()=>xs,ClerkJwtInboundPolicy:()=>vs,CognitoJwtInboundPolicy:()=>Ss,CompositeInboundPolicy:()=>Ts,ConfigurationError:()=>m,ContentTypes:()=>At,ContextData:()=>X,CryptoBeta:()=>An,CurityPhantomTokenInboundPolicy:()=>Os,DataDogLoggingPlugin:()=>Wt,DataDogMetricsPlugin:()=>ln,DynaTraceLoggingPlugin:()=>on,DynatraceMetricsPlugin:()=>dn,FirebaseJwtInboundPolicy:()=>Cs,FormDataToJsonInboundPolicy:()=>As,GeoFilterInboundPolicy:()=>Ls,GoogleCloudLoggingPlugin:()=>zt,Handler:()=>nn,HttpProblems:()=>R,HttpStatusCode:()=>kt,InboundPolicy:()=>ee,JWTScopeValidationInboundPolicy:()=>_s,KeyValueStore:()=>_n,LokiLoggingPlugin:()=>sn,LookupResult:()=>He,MemoryZoneReadThroughCache:()=>Z,MockApiInboundPolicy:()=>Hs,MoesifInboundPolicy:()=>Bs,MonetizationPolicy:()=>Rn,OktaJwtInboundPolicy:()=>js,OpenIdJwtInboundPolicy:()=>F,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>ge,PropelAuthJwtInboundPolicy:()=>Gs,RateLimitInboundPolicy:()=>co,ReadmeMetricsInboundPolicy:()=>Ys,RemoveHeadersInboundPolicy:()=>Qs,RemoveHeadersOutboundPolicy:()=>Xs,RemoveQueryParamsInboundPolicy:()=>ea,ReplaceStringOutboundPolicy:()=>ta,RequestSizeLimitInboundPolicy:()=>ra,RequestValidationInboundPolicy:()=>mo,RequireOriginInboundPolicy:()=>da,ResponseSendingEvent:()=>ke,ResponseSentEvent:()=>De,Router:()=>Ne,RuntimeError:()=>I,SYSTEM_LOGGER:()=>st,SchemaBasedRequestValidation:()=>la,ServiceProviderImpl:()=>On,SetBodyInboundPolicy:()=>pa,SetHeadersInboundPolicy:()=>ma,SetHeadersOutboundPolicy:()=>ga,SetQueryParamsInboundPolicy:()=>fa,SetStatusOutboundPolicy:()=>ha,SleepInboundPolicy:()=>ya,StripeMeteringPlugin:()=>to,StripeWebhookVerificationInboundPolicy:()=>Be,SumoLogicLoggingPlugin:()=>an,SupabaseJwtInboundPolicy:()=>ba,SystemLogMap:()=>O,SystemRouteName:()=>ie,UpstreamAzureAdServiceAuthInboundPolicy:()=>wa,UpstreamFirebaseAdminAuthInboundPolicy:()=>Pa,UpstreamFirebaseUserAuthInboundPolicy:()=>Ia,UpstreamGcpJwtInboundPolicy:()=>Ea,UpstreamGcpServiceAuthInboundPolicy:()=>va,VMWareLogInsightLoggingPlugin:()=>un,ValidateJsonSchemaInbound:()=>Sa,ZoneCache:()=>de,ZuploRequest:()=>L,awsLambdaHandler:()=>Ji,environment:()=>z,getIdForParameterSchema:()=>Sn,getIdForRefSchema:()=>ia,getIdForRequestBodySchema:()=>Tn,getRawOperationDataIdentifierName:()=>oa,httpStatuses:()=>Dt,isRestrictedEnvVariableName:()=>Tr,isZuploReadableEnvVariableName:()=>Or,openApiSpecHandler:()=>Yi,originalFetch:()=>Ze,purgeGatewayCache:()=>Ni,redirectHandler:()=>Qi,sanitizedIdentifierName:()=>we,serialize:()=>Lt,setMoesifContext:()=>Fs,urlForwardHandler:()=>Xi,urlRewriteHandler:()=>es,webSocketHandler:()=>ts,webSocketPipelineHandler:()=>os});module.exports=Ma(ql);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=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"}},m=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},wt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var h=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 Rt=globalThis,Po=Rt.caches;if(Po){let t=Po.open;Rt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Rt.caches.default,Object.freeze(Rt.caches)}var Io=new Map,Dn=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)})}},Le=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Io.get(e);r||(r=new Dn(n),Io.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 Mn="__zuplo-expiry-header",de=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(Mn);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(Mn,`${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(Mn,`${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 Z=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Le(r),this.#n=new de(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 Eo="zuplo-request-id",Ye="zp-rid",xo="zp-body-removed",_e="cf-ray",Un="cf-ipcity",Hn="cf-ipcontinent",Nn="cf-ipcountry",Zn="cf-iplongitude",qn="cf-iplatitude",vo="zp-ipcity",So="zp-ipcontinent",To="zp-ipcountry",Oo="zp-iplongitude",Co="zp-iplatitude",Ao="true-client-ip",$n="zp-asn",Fn="zp-asorg",Bn="zp-colo",jn="zp-postalcode",zn="zp-metrocode",Gn="zp-region",Vn="zp-regioncode",Wn="zp-timezone",Lo=[Un,Hn,Nn,Zn,qn,$n,Fn,Bn,jn,zn,Gn,Vn,Wn],_o=["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"],Qe="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Pt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Ci=Ae(Pe());var et=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 I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ge=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await et.problemResponseFormat(e,n,r)}};function Ot(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ot(n)}return Object.freeze(t)}s(Ot,"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 Ot(this.#e)}get params(){return Ot(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ce=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},tt={},fe=[],Yo=[],Qo=[],Xo=[];var Ct={addPlugin(t){fe.push(t)},addRequestHook(t){Yo.push(t)},addResponseSendingHook(t){Qo.push(t)},addResponseSendingFinalHook(t){Xo.push(t)}},ei=s(async(t,e)=>{let n=t;for(let r of Yo){let o=await r(n,e);if(o instanceof L)n=o;else{if(o instanceof Response)return o;throw new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),ti=s(async(t,e,n)=>{let r=t;for(let o of Qo){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),ni=s(async(t,e,n)=>{for(let r of Xo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ri(t=()=>Promise.resolve()){await t(Ct),tt.value=Ct;for(let e of fe)e instanceof ce&&await e.initialize(Ct);et.setProblemResponseFormat(Ct.problemResponseFormat)}s(ri,"initializeRuntime");var At={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Lt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(At.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(At.Json)||!e?JSON.stringify(t):t}s(Lt,"serialize");function nt(t){return q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(nt,"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 P=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async A=>{let N=await r(A,i);return Fu(N)},n)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(nt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ke(o,l);i.dispatchEvent(p);let y=B.getContextExtensions(i),g=y.latestRequest,w;try{w=await p.mutableResponse}catch(P){return i.log.error(P),n.errorHandler(o,i,P)}try{w=await y.onResponseSending(w,g,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}try{w=await ti(w,g,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}i.dispatchEvent(new De(o,w));try{await y.onResponseSendingFinal(l,g,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await ni(l,g,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return w}};function Fu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Lt(t),{headers:{"content-type":"application/json"}})}s(Fu,"resultToResponse");var he=class extends Ie{static{s(this,"MetricsPlugin")}};var O=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 _t=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,O.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}=h.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":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!u.ok){let c=await u.text();O.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=rt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},rt={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(_e)??void 0,c=t.headers.get(Ao)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,y={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},g=[];return g.push(new _t(e)),fe.forEach(w=>{if(w instanceof he){let P=w.getTransport();g.push(P)}}),g.forEach(w=>{w.pushMetrics(y,e)}),a},"metricsProcessor");var ie=(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))(ie||{});var rr=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=h.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"&&O.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 kt=(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))(kt||{}),oi={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 Bu={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"},Dt=Bu;function ju(t){return`${new URL(t.url).pathname}`}s(ju,"instance");function zu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(_e);return r&&(n.rayId=r),n}s(zu,"trace");var Gu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:ju(e),trace:zu(e,n),...r},additionalHeaders:o,statusText:Dt[t.status]}),"merge"),or=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ge.format(e,n,r):ge.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:oi[e],...n}}},R=class extends or{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Gu(this.getProblemFromStatus(e),n,r,o,i);return ge.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:Vu}=Object.prototype,{propertyIsEnumerable:Wu}=Object.prototype;function ir(t){return Vu.call(t)}s(ir,"toString");function W(t){return typeof t=="string"}s(W,"isString");function Me(t){return W(t)&&t!==""}s(Me,"isNonEmptyString");function ii(t){return ir(t)==="[object RegExp]"}s(ii,"isRegexp");function si(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Wu.call(t,e))]}s(si,"getOwnEnumerableKeys");function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Ee,"isObject");function sr(t){return typeof t=="number"&&!isNaN(t)}s(sr,"isNumber");function ar(t){return t===!0||t===!1}s(ar,"isBoolean");function ai(t){return typeof t>"u"}s(ai,"isUndefined");function ui(t){return ai(t)||t===null}s(ui,"isUndefinedOrNull");function ot(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ot,"isErrorLike");var ci=new Map;function Mt(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=ci.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 ci.set(t,r),r}s(Mt,"statusCodesStringToNumberArray");function xe(t,e,n){if(!e.startsWith("."))throw new m(`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 I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function ve(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new m("Received an array that contains non-string values.");return t}if(W(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new m(`Expected type of string, received type '${typeof t}'`)}s(ve,"parseValueToStringArray");function li(t){if(t==null)return[];if(!Array.isArray(t))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Ee(n))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Me(n.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!sr(n.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!ar(n.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=ur(n,"allowedHeaders"),o=ur(n,"allowedMethods"),i=ur(n,"exposeHeaders"),a;try{a=ve(n.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(li,"parseCorsPolicies");function ur(t,e){let n;if(t[e]!==void 0)try{n=ve(t[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(ur,"parseOptionalProperty");var Ut=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"),Ht=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 cr=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 y=t.lookup(l,c);if(!y)return R.notFound(a,u);let g=y.routeConfiguration,w=Ku(l,d,p,g,n);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&u.log.warn(w.error),R.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"),Ku=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 m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ut(a.allowedOrigins,n);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var di=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 lr=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),pi=s((t,e)=>{let n=s(async(o,i)=>{let a=tt.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new D({processors:[j],handler:n,gateway:e});t.addRoute(lr,r.execute)},"registerNotMatchedHandler");var Ju=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],mi=s(t=>{Ju.forEach(e=>t.delete(e))},"stripCorsHeaders"),Nt=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 mi(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=Yu(o,n.routeData.corsPolicies),u=Qu(t,a),c=new Headers(i.headers);return mi(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"),Yu=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 m(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Qu=s((t,e)=>{let n=Ut(e.allowedOrigins,t.headers.get("origin"));return n?Ht(e,n):{}},"getCorsHeaders");var dr=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new D({processors:[Nt],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");var Zt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!W(n))throw new I(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},ee=class extends Zt{static{s(this,"InboundPolicy")}},Se=class extends Zt{static{s(this,"OutboundPolicy")}};var gr=class extends ee{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},fr=class extends Se{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},pr=new Map;function it(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!pr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ee)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new gr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);pr.set(a.name,c)}),n.map(i=>{let a=pr.get(i);if(a===void 0)throw new I("Internal error. Policy not found in cache.");return a})}s(it,"getInboundPolicyInstances");var mr=new Map;function Xu(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!mr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new fr(a,i.handler.options,i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);mr.set(i.name,u)}),n.map(o=>{let i=mr.get(o);if(i===void 0)throw new I("Internal error. Policy not found in cache.");return i})}s(Xu,"getOutboundPolicyInstances");var hr=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);if(u instanceof L)i=u;else if(u instanceof Request)i=new L(u);else{if(u instanceof Response)return u;throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),ec=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),qt=s(async(t,e,n,r)=>{let o=it(e.route,n.routeData.policies),i=Xu(e.route,n.routeData.policies);return fi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function gi({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>fi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(gi,"createInternalPolicyProcessor");async function fi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=hr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=ec(r),d;return h.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(fi,"executePolicyProcessor");function hi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||tc,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]=nc(l,o)}i=u+1}return n}s(hi,"parse");function tc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(tc,"decode");function nc(t,e){try{return e(t)}catch{return t}}s(nc,"tryDecode");function yi(t,e){try{let n=/v\d+(-\d+)?/g,o=hi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(yi,"devPortalBaseURL");var bi="/__zuplo/dev-portal",rc="dev-portal-id",oc="dev-portal-host",ic="zp-account",sc="zp-project",ac="dev-portal-build",uc=`
|
|
35
|
+
`)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(Du,"reduceToSingleString")});var Ko=Je(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.format=void 0;var Mu=Fo(),Uu=Wo(),Hu=s((t,...e)=>(0,Mu.format)(Uu.inspect,t,e),"format");vt.format=Hu});var Pe=Je(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.debug=me.withoutEnv=me.Debugger=void 0;var Nu=$o(),Zu=Ko(),St=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Nu.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,Zu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};me.Debugger=St;var Tt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Jo(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Jo,"extract");var Xe;function qu(t){t||(t=[]),typeof t=="string"&&(t=Jo(t)),Xe=new Tt(t)}s(qu,"withoutEnv");me.withoutEnv=qu;function $u(t){let e=globalThis.DEBUG;Xe||(Xe=new Tt(Jo(e)));let n=new St(Xe,t);return Xe.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s($u,"debug");me.debug=$u});var ql={};Da(ql,{API_KEY:()=>Pi,AWSLoggingPlugin:()=>cn,AmberfloMeteringInboundPolicy:()=>fs,AmberfloMeteringPolicy:()=>hn,ApiAuthKeyInboundPolicy:()=>bs,ApiKeyInboundPolicy:()=>bn,AuditLogDataStaxProvider:()=>pn,AuditLogPlugin:()=>mn,Auth0JwtInboundPolicy:()=>ws,AwsLambdaHandlerExtensions:()=>Ki,BasicAuthInboundPolicy:()=>Rs,BasicRateLimitInboundPolicy:()=>co,CachingInboundPolicy:()=>Ps,ChangeMethodInboundPolicy:()=>Is,ClearHeadersInboundPolicy:()=>Es,ClearHeadersOutboundPolicy:()=>xs,ClerkJwtInboundPolicy:()=>vs,CognitoJwtInboundPolicy:()=>Ss,CompositeInboundPolicy:()=>Ts,ConfigurationError:()=>m,ContentTypes:()=>At,ContextData:()=>X,CryptoBeta:()=>An,CurityPhantomTokenInboundPolicy:()=>Os,DataDogLoggingPlugin:()=>Wt,DataDogMetricsPlugin:()=>ln,DynaTraceLoggingPlugin:()=>on,DynatraceMetricsPlugin:()=>dn,FirebaseJwtInboundPolicy:()=>Cs,FormDataToJsonInboundPolicy:()=>As,GeoFilterInboundPolicy:()=>Ls,GoogleCloudLoggingPlugin:()=>zt,Handler:()=>nn,HttpProblems:()=>R,HttpStatusCode:()=>kt,InboundPolicy:()=>ee,JWTScopeValidationInboundPolicy:()=>_s,KeyValueStore:()=>_n,LokiLoggingPlugin:()=>sn,LookupResult:()=>He,MemoryZoneReadThroughCache:()=>Z,MockApiInboundPolicy:()=>Hs,MoesifInboundPolicy:()=>Bs,MonetizationInboundPolicy:()=>Rn,OktaJwtInboundPolicy:()=>js,OpenIdJwtInboundPolicy:()=>F,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>ge,PropelAuthJwtInboundPolicy:()=>Gs,RateLimitInboundPolicy:()=>co,ReadmeMetricsInboundPolicy:()=>Ys,RemoveHeadersInboundPolicy:()=>Qs,RemoveHeadersOutboundPolicy:()=>Xs,RemoveQueryParamsInboundPolicy:()=>ea,ReplaceStringOutboundPolicy:()=>ta,RequestSizeLimitInboundPolicy:()=>ra,RequestValidationInboundPolicy:()=>mo,RequireOriginInboundPolicy:()=>da,ResponseSendingEvent:()=>ke,ResponseSentEvent:()=>De,Router:()=>Ne,RuntimeError:()=>I,SYSTEM_LOGGER:()=>st,SchemaBasedRequestValidation:()=>la,ServiceProviderImpl:()=>On,SetBodyInboundPolicy:()=>pa,SetHeadersInboundPolicy:()=>ma,SetHeadersOutboundPolicy:()=>ga,SetQueryParamsInboundPolicy:()=>fa,SetStatusOutboundPolicy:()=>ha,SleepInboundPolicy:()=>ya,StripeMeteringPlugin:()=>to,StripeWebhookVerificationInboundPolicy:()=>Be,SumoLogicLoggingPlugin:()=>an,SupabaseJwtInboundPolicy:()=>ba,SystemLogMap:()=>O,SystemRouteName:()=>ie,UpstreamAzureAdServiceAuthInboundPolicy:()=>wa,UpstreamFirebaseAdminAuthInboundPolicy:()=>Pa,UpstreamFirebaseUserAuthInboundPolicy:()=>Ia,UpstreamGcpJwtInboundPolicy:()=>Ea,UpstreamGcpServiceAuthInboundPolicy:()=>va,VMWareLogInsightLoggingPlugin:()=>un,ValidateJsonSchemaInbound:()=>Sa,ZoneCache:()=>de,ZuploRequest:()=>L,awsLambdaHandler:()=>Ji,environment:()=>z,getIdForParameterSchema:()=>Sn,getIdForRefSchema:()=>ia,getIdForRequestBodySchema:()=>Tn,getRawOperationDataIdentifierName:()=>oa,httpStatuses:()=>Dt,isRestrictedEnvVariableName:()=>Tr,isZuploReadableEnvVariableName:()=>Or,openApiSpecHandler:()=>Yi,originalFetch:()=>Ze,purgeGatewayCache:()=>Ni,redirectHandler:()=>Qi,sanitizedIdentifierName:()=>we,serialize:()=>Lt,setMoesifContext:()=>Fs,urlForwardHandler:()=>Xi,urlRewriteHandler:()=>es,webSocketHandler:()=>ts,webSocketPipelineHandler:()=>os});module.exports=Ma(ql);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=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"}},m=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},wt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var h=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 Rt=globalThis,Po=Rt.caches;if(Po){let t=Po.open;Rt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Rt.caches.default,Object.freeze(Rt.caches)}var Io=new Map,Dn=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)})}},Le=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=Io.get(e);r||(r=new Dn(n),Io.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 Mn="__zuplo-expiry-header",de=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(Mn);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(Mn,`${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(Mn,`${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 Z=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Le(r),this.#n=new de(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 Eo="zuplo-request-id",Ye="zp-rid",xo="zp-body-removed",_e="cf-ray",Un="cf-ipcity",Hn="cf-ipcontinent",Nn="cf-ipcountry",Zn="cf-iplongitude",qn="cf-iplatitude",vo="zp-ipcity",So="zp-ipcontinent",To="zp-ipcountry",Oo="zp-iplongitude",Co="zp-iplatitude",Ao="true-client-ip",$n="zp-asn",Fn="zp-asorg",Bn="zp-colo",jn="zp-postalcode",zn="zp-metrocode",Gn="zp-region",Vn="zp-regioncode",Wn="zp-timezone",Lo=[Un,Hn,Nn,Zn,qn,$n,Fn,Bn,jn,zn,Gn,Vn,Wn],_o=["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"],Qe="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Pt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91";var Ci=Ae(Pe());var et=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 I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ge=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await et.problemResponseFormat(e,n,r)}};function Ot(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Ot(n)}return Object.freeze(t)}s(Ot,"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 Ot(this.#e)}get params(){return Ot(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ce=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},tt={},fe=[],Yo=[],Qo=[],Xo=[];var Ct={addPlugin(t){fe.push(t)},addRequestHook(t){Yo.push(t)},addResponseSendingHook(t){Qo.push(t)},addResponseSendingFinalHook(t){Xo.push(t)}},ei=s(async(t,e)=>{let n=t;for(let r of Yo){let o=await r(n,e);if(o instanceof L)n=o;else{if(o instanceof Response)return o;throw new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),ti=s(async(t,e,n)=>{let r=t;for(let o of Qo){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),ni=s(async(t,e,n)=>{for(let r of Xo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ri(t=()=>Promise.resolve()){await t(Ct),tt.value=Ct;for(let e of fe)e instanceof ce&&await e.initialize(Ct);et.setProblemResponseFormat(Ct.problemResponseFormat)}s(ri,"initializeRuntime");var At={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Lt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(At.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(At.Json)||!e?JSON.stringify(t):t}s(Lt,"serialize");function nt(t){return q.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(q.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(nt,"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 P=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async A=>{let N=await r(A,i);return Fu(N)},n)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(nt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ke(o,l);i.dispatchEvent(p);let y=B.getContextExtensions(i),g=y.latestRequest,w;try{w=await p.mutableResponse}catch(P){return i.log.error(P),n.errorHandler(o,i,P)}try{w=await y.onResponseSending(w,g,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}try{w=await ti(w,g,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}i.dispatchEvent(new De(o,w));try{await y.onResponseSendingFinal(l,g,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await ni(l,g,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return w}};function Fu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Lt(t),{headers:{"content-type":"application/json"}})}s(Fu,"resultToResponse");var he=class extends Ie{static{s(this,"MetricsPlugin")}};var O=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 _t=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,O.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}=h.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":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!u.ok){let c=await u.text();O.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=rt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},rt={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(_e)??void 0,c=t.headers.get(Ao)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,y={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},g=[];return g.push(new _t(e)),fe.forEach(w=>{if(w instanceof he){let P=w.getTransport();g.push(P)}}),g.forEach(w=>{w.pushMetrics(y,e)}),a},"metricsProcessor");var ie=(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))(ie||{});var rr=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=h.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"&&O.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 kt=(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))(kt||{}),oi={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 Bu={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"},Dt=Bu;function ju(t){return`${new URL(t.url).pathname}`}s(ju,"instance");function zu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(_e);return r&&(n.rayId=r),n}s(zu,"trace");var Gu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:ju(e),trace:zu(e,n),...r},additionalHeaders:o,statusText:Dt[t.status]}),"merge"),or=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ge.format(e,n,r):ge.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:oi[e],...n}}},R=class extends or{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Gu(this.getProblemFromStatus(e),n,r,o,i);return ge.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:Vu}=Object.prototype,{propertyIsEnumerable:Wu}=Object.prototype;function ir(t){return Vu.call(t)}s(ir,"toString");function W(t){return typeof t=="string"}s(W,"isString");function Me(t){return W(t)&&t!==""}s(Me,"isNonEmptyString");function ii(t){return ir(t)==="[object RegExp]"}s(ii,"isRegexp");function si(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Wu.call(t,e))]}s(si,"getOwnEnumerableKeys");function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Ee,"isObject");function sr(t){return typeof t=="number"&&!isNaN(t)}s(sr,"isNumber");function ar(t){return t===!0||t===!1}s(ar,"isBoolean");function ai(t){return typeof t>"u"}s(ai,"isUndefined");function ui(t){return ai(t)||t===null}s(ui,"isUndefinedOrNull");function ot(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ot,"isErrorLike");var ci=new Map;function Mt(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=ci.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 ci.set(t,r),r}s(Mt,"statusCodesStringToNumberArray");function xe(t,e,n){if(!e.startsWith("."))throw new m(`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 I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function ve(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new m("Received an array that contains non-string values.");return t}if(W(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new m(`Expected type of string, received type '${typeof t}'`)}s(ve,"parseValueToStringArray");function li(t){if(t==null)return[];if(!Array.isArray(t))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Ee(n))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Me(n.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!sr(n.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!ar(n.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=ur(n,"allowedHeaders"),o=ur(n,"allowedMethods"),i=ur(n,"exposeHeaders"),a;try{a=ve(n.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(li,"parseCorsPolicies");function ur(t,e){let n;if(t[e]!==void 0)try{n=ve(t[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(ur,"parseOptionalProperty");var Ut=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"),Ht=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 cr=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 y=t.lookup(l,c);if(!y)return R.notFound(a,u);let g=y.routeConfiguration,w=Ku(l,d,p,g,n);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&u.log.warn(w.error),R.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"),Ku=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 m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ut(a.allowedOrigins,n);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var di=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 lr=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),pi=s((t,e)=>{let n=s(async(o,i)=>{let a=tt.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new D({processors:[j],handler:n,gateway:e});t.addRoute(lr,r.execute)},"registerNotMatchedHandler");var Ju=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],mi=s(t=>{Ju.forEach(e=>t.delete(e))},"stripCorsHeaders"),Nt=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 mi(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=Yu(o,n.routeData.corsPolicies),u=Qu(t,a),c=new Headers(i.headers);return mi(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"),Yu=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 m(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Qu=s((t,e)=>{let n=Ut(e.allowedOrigins,t.headers.get("origin"));return n?Ht(e,n):{}},"getCorsHeaders");var dr=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new D({processors:[Nt],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");var Zt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!W(n))throw new I(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},ee=class extends Zt{static{s(this,"InboundPolicy")}},Se=class extends Zt{static{s(this,"OutboundPolicy")}};var gr=class extends ee{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},fr=class extends Se{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},pr=new Map;function it(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!pr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ee)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new gr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);pr.set(a.name,c)}),n.map(i=>{let a=pr.get(i);if(a===void 0)throw new I("Internal error. Policy not found in cache.");return a})}s(it,"getInboundPolicyInstances");var mr=new Map;function Xu(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!mr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new fr(a,i.handler.options,i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);mr.set(i.name,u)}),n.map(o=>{let i=mr.get(o);if(i===void 0)throw new I("Internal error. Policy not found in cache.");return i})}s(Xu,"getOutboundPolicyInstances");var hr=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);if(u instanceof L)i=u;else if(u instanceof Request)i=new L(u);else{if(u instanceof Response)return u;throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),ec=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),qt=s(async(t,e,n,r)=>{let o=it(e.route,n.routeData.policies),i=Xu(e.route,n.routeData.policies);return fi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function gi({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>fi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(gi,"createInternalPolicyProcessor");async function fi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=hr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=ec(r),d;return h.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(fi,"executePolicyProcessor");function hi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||tc,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]=nc(l,o)}i=u+1}return n}s(hi,"parse");function tc(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(tc,"decode");function nc(t,e){try{return e(t)}catch{return t}}s(nc,"tryDecode");function yi(t,e){try{let n=/v\d+(-\d+)?/g,o=hi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(yi,"devPortalBaseURL");var bi="/__zuplo/dev-portal",rc="dev-portal-id",oc="dev-portal-host",ic="zp-account",sc="zp-project",ac="dev-portal-build",uc=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -68,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
68
68
|
`+d}):new ue(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 ue(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(il,"validateComputedSignature");function sl(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(sl,"parseHeader");function al(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(al,"secureCompare");async function ul(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]=Jr[i[u]];return a.join("")}s(ul,"computeHMACSignatureAsync");var Jr=new Array(256);for(let t=0;t<Jr.length;t++)Jr[t]=t.toString(16).padStart(2,"0");function H(t,e){if(!Ee(t))throw new m(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new m(`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 m(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new m(`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 m(`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 m(`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(H,"optionValidator");var Be=class extends ee{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){H(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ss(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),R.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function as(t){return t!==null&&typeof t=="object"&&"id"in t&&W(t.id)&&"type"in t&&W(t.type)}s(as,"isStripeWebhookEvent");var gn=class extends ce{static{s(this,"MeteringPlugin")}};var cl={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 I(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 I(i)}return o}},us=cl;var Yr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function cs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${t}/consumers`,Yr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),y=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,y),new I(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(cs,"createConsumer");async function ls({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${t}/consumers`,Yr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await V({retryDelayMs:5,retries:2,logger:O.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let y="Error creating API Key Consumer";throw i.log.error(y,p),new I(y)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(ls,"createConsumerInvite");async function ds({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Yr);o.searchParams.set("with-api-key","true");let i=await V({retryDelayMs:5,retries:2,logger:O.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new I(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(ds,"deleteConsumer");async function ps({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=h.instance;if(!Me(l))throw new T("No Zuplo JWT token set.");let p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let y="Error creating metering subscription.",g;try{g=await p.json()}catch{g={status:p.status,statusText:p.statusText}}throw t.log.error(y,g),new I(y)}t.log.info("Successfully created/updated metering subscription.",c)}s(ps,"createSubscription");async function gt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Me(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new I(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(gt,"updateSubscription");async function ft({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Me(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new I(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}return u.data[0]}s(ft,"getSubscription");function fn(t){return t.replaceAll("_","-")}s(fn,"stripeStatusToMeteringStatus");async function Qr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await cs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await us.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return R.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=fn(n.data.object.status);await ps({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await ds({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),R.internalServerError(t,e,{detail:l.message})}return R.ok(t,e)}s(Qr,"onCustomerSubscriptionCreated");async function Xr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),R.ok(t,e)}s(Xr,"onCustomerSubscriptionDeleted");async function eo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=fn(n.data.object.status);return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),R.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[n.data.object.plan.product]}}),R.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),R.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(eo,"onCustomerSubscriptionUpdated");var to=class extends gn{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(z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let y=this.options.meteringBucketRegion??"us-central1";if(!ll(y))throw new m(`StripeMeteringPlugin - The value '${y}' on the property 'meteringBucketRegion' is invalid.`);let g=await c.json();if(!as(g))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 '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Qr(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await eo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Xr(c,l,g,{meteringBucketId:d});default:return R.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=gi({inboundPolicies:[new Be({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),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 ll(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(ll,"isMetricsRegion");var gs=new WeakMap,ms={},hn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){gs.set(e,n)}};async function fs(t,e,n,r){if(!n.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Mt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=gs.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(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)},y=ms[n.apiKey];if(!y){let g=n.apiKey,w=t.headers.get("zm-test-id")??"";y=new C("amberflo-ingest-meter",10,async P=>{try{let E=n.url??"https://app.amberflo.io/ingest",x=await fetch(E,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),ms[g]=y}y.enqueue(p),e.waitUntil(y.waitUntilFlushed())}}),t}s(fs,"AmberfloMeteringInboundPolicy");async function yn(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(yn,"sha256");var hs=new Map;async function $(t,e){let n,r=hs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await yn(JSON.stringify({policyName:t,options:e}))}`,hs.set(t,n)),n}s($,"getPolicyCacheName");var ys="key-metadata-cache-type";function dl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(dl,"getKeyValue");async function bn(t,e,n,r){if(!n.bucketName)if(z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`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 m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(E=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:E}),"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=dl(a,o);if(!u||u==="")return i("No key present");let c=await pl(u),l=await $(r,o),d=new Z(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!==ys&&O.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let y={key:u},g=await V({retryDelayMs:5,retries:2,logger:O.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(y)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let E=await g.text(),x=JSON.parse(E);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let w=await g.json(),P={isValid:!0,typeId:ys,user:{sub:w.name,data:w.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(bn,"ApiKeyInboundPolicy");async function pl(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(pl,"hashValue");var bs=bn;var ht=require("jose");var no={},ml=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");no[e.jwkUrl]||(no[e.jwkUrl]=(0,ht.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ht.jwtVerify)(t,no[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),gl=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,ht.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),F=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(y=>R.unauthorized(t,e,{detail:y}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?ml:gl,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 y=o.substring(i.length);if(!y||y.length===0)return a("No bearer token on authorization header");try{return await u(y,n)}catch(g){let w=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,g),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 ws=s(async(t,e,n,r)=>F(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Rs=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 y=d.substring(0,p),g=d.substring(p+1),w=n.accounts.find(P=>P.username===y&&P.password===g);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 fl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function hl(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(hl,"digestMessage");var yl=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 hl(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 Ps(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await yl(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 y=n?.expirationSecondsTtl??60,g=new Response(p.body,p);fl.forEach(w=>g.headers.delete(w)),g.headers.set("cache-control",`s-maxage=${y}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ps,"CachingInboundPolicy");var Is=s(async(t,e,n,r)=>{if(!n.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Es=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 xs=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 vs=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",F(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 m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return F(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 Ts=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=q.instance,i=it(n.policies,o?.routeData.policies);return hr(i)(t,e)},"CompositeInboundPolicy");var Os=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=bl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(r,n),u=new Z(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 bl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(bl,"getToken");var Cs=s(async(t,e,n,r)=>(H(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),F(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 As=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 je="__unknown__",Ls=s(async(t,e,n,r)=>{let o={allow:{countries:Ge(n.allow?.countries,"allow.countries",r),regionCodes:Ge(n.allow?.regionCodes,"allow.regionCode",r),asns:Ge(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ge(n.block?.countries,"block.countries",r),regionCodes:Ge(n.block?.regionCodes,"block.regionCode",r),asns:Ge(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??je,a=e.incomingRequestProperties.regionCode?.toLowerCase()??je,u=e.incomingRequestProperties.asn?.toString()??je,c=o.ignoreUnknown&&i===je,l=o.ignoreUnknown&&a===je,d=o.ignoreUnknown&&u===je,p=o.allow.countries,y=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||y.length>0&&!y.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ze(t,e,r,i,a,u);let w=o.block.countries,P=o.block.regionCodes,E=o.block.asns;return w.length>0&&w.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ze(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(ze,"blockedResponse");function Ge(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 m(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ge,"toLowerStringArray");var _s=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");async function ks(t,e,n,r){let o=O.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=h.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(ks,"loadSubscription");async function Ds(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=h.instance,u=O.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(Ds,"consumeSubcriptionQuotas");var wl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function wn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new m(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(wn,"validateMeters");function Ms(t,e){if(t)try{if(t.length===0)throw new m("Must set valid subscription statuses");let n=ve(t),r=[];for(let o of n)wl.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(Ms,"parseAllowedSubscriptionStatuses");var Rn=class extends ee{static{s(this,"MonetizationPolicy")}static getSubscription(e){return X.get(e,Qe)}static setMeters(e,n){wn(n,"setMeters"),X.set(e,Pt,n)}async handler(e,n){if(H(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new m(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let r=this.options.allowRequestsOverQuota??!1,o=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:Mt(this.options.meterOnStatusCodes),i=X.get(n,Pt),a={...this.options.meters,...i};wn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ms(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(P,E,x)=>{let A=X.get(x,Qe);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){x.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(z.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let _=X.get(x,Pt),M={...this.options.meters,..._};wn(M,this.policyName),o.includes(P.status)&&A&&M&&(x.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(M)} on response status '${P.status}'`),await Ds(x,A.id,this.policyName,this.options.bucketId,M))});let l=e.user;if(!l)return u?e:R.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(z.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ks(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:R.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),R.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),X.set(n,Qe,p));let y=X.get(n,Qe);if(!y)return u?e:(n.log.warn("Subscription is not available for user"),R.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(y&&Object.keys(y.meters).length===0)return n.log.error(`Quota is not set up for subscription '${y.id}'`),R.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let w=Object.keys(a).filter(P=>!Object.keys(y.meters).includes(P));if(w.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${w.join(", ")}`),R.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${w.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(y.meters[P].consumed<=0&&!r)return R.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Hs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return ro(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 ro(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(y=>{a.push({responseName:u,contentName:l,exampleName:y,exampleValue:d[y]})})})}),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 Us(a[u])}else return a.length>0?Us(a[0]):ro(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 Us(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(Us,"generateResponse");var ro=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",Pl={logRequestBody:!0,logResponseBody:!0};function Ns(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ns,"headersToObject");function Zs(){return new Date().toISOString()}s(Zs,"timestamp");var oo=new WeakMap,Il={};function Fs(t,e){let n=oo.get(t);n||(n=Il);let r=Object.assign({...n},e);oo.set(t,r)}s(Fs,"setMoesifContext");async function qs(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(qs,"readBody");var El={},io;function $s(){if(!io)throw new I("Invalid State - no _lastLogger");return io}s($s,"getLastLogger");function xl(t){let e=El[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);$s().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||$s().error({status:o.status,body:await o.text()})})),e}s(xl,"getDispatcher");async function Bs(t,e,n,r){io=e.log;let o=Zs(),i=Object.assign(Pl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await qs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=xl(i.applicationId),d=t.headers.get("true-client-ip"),p=oo.get(e)??{},y={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ns(t.headers)},g=i.logResponseBody?await qs(u,e):void 0,w={time:Zs(),status:u.status,headers:Ns(u.headers),body:g},P={request:y,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Rl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(Bs,"MoesifInboundPolicy");var js=s(async(t,e,n,r)=>F(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var zs=require("jose");var so,Gs=s(async(t,e,n,r)=>{if(!so)try{so=await(0,zs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:so,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ws=Ae(Pe());var Pn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ao=class extends Pn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},uo=class extends Pn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function vl(t,e){if(ui(t))throw new ao(e)}s(vl,"throwIfUndefinedOrNull");function yt(t,e){if(vl(t,e),!W(t))throw new uo(e,"string")}s(yt,"throwIfNotString");var In=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 yt(e,"redisClientUrl"),yt(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}){yt(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)}`)}},En=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(yt(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 xn=(0,Ws.debug)("zuplo:policies:RateLimitInboundPolicy"),Sl="strict",Tl=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"),Ol=s(async t=>({key:`ip-${Tl(t)}`}),"getIP"),Cl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Al=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),vn;function Ll(t,e){let n;if(vn)return vn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new En,vn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!W(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!W(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=In.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return vn=n,n}s(Ll,"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 _l(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new m(`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 m(`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 I(c)}return u},"outerFunction")}s(_l,"wrapUserFunction");var kl="Retry-After",co=s(async(t,e,n,r)=>{let o=Date.now(),i=O.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[kl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:_l(n,r),user:Cl,ip:Ol,all:Al}[n.rateLimitBy],d=await l(t,e,r),p=d.key,y=d.requestsAllowed??n.requestsAllowed,g=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",P=Ll(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Sl)==="async"){let _=await $(r,n),M=new de(_,{logger:O.getLogger(e)}),Y=Vs(x,g,P,i,e.requestId),Q=await M.get(x);if(Q!==void 0&&Q<=Date.now()){xn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Oe=Math.round((Q-Date.now())/1e3);return u(w,Oe)}return e.addEventListener("responseSending",Oe=>{try{let Ce=Oe,kn=Ce.mutableResponse;Ce.mutableResponse=(async()=>{let bt=await Y;if(bt.count>y){let Ta=Date.now()+bt.ttlSeconds*1e3,Oa=M.put(x,Ta,bt.ttlSeconds).catch(wo=>{throw i.error(new T("Error caching rate limit result.",{cause:wo})),wo});return e.waitUntil(Oa),xn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,bt.ttlSeconds)}return kn})()}catch(Ce){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ce)}}),t}let N=await Vs(x,g,P,i,e.requestId);return N.count>y?(xn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,N.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;xn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var lo;function Ks(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ks,"headersToNameValuePairs");function Dl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Dl,"queryToNameValueParis");function Ml(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Ml,"parseIntOrUndefined");var Js={};async function Ys(t,e,n,r){let o=new Date,i=Date.now();return lo||(lo={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:lo,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:Ks(t.headers),queryString:Dl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ks(a.headers),content:{size:Ml(t.headers.get("content-length"))}}}]}}},d=Js[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async y=>{try{let g=n.url??"https://metrics.readme.io/request",w=await fetch(g,{method:"POST",body:JSON.stringify(y),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(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Js[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Ys,"ReadmeMetricsInboundPolicy");var Qs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Xs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`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 ea=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ta=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 na=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ra=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?na():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?na():t},"RequestSizeLimitInboundPolicy");function oa(t,e,n){return`_${we(t+"_"+e+"_"+n)}`}s(oa,"getRawOperationDataIdentifierName");function Sn(t,e,n,r){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Sn,"getIdForParameterSchema");function Tn(t,e,n){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${we(n.toLowerCase())}`}s(Tn,"getIdForRequestBodySchema");function ia(t,e){return`_${we(t)}__${we(e)}`}s(ia,"getIdForRefSchema");function we(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(we,"sanitizedIdentifierName");var Ve=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"),We=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=Sn(n,r,o,c.name),p=q.instance.schemaValidator[d],y=p(e[c.name]),g=po(p.errors);y||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ne=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),re=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),oe=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),po=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 sa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=R.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${g}`});if(re(n.validateBody)&&ne(t,n.logLevel??"info",w,[r],g),oe(n.validateBody))return P}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=R.badRequest(e,t,{detail:g});return re(n.validateBody)&&ne(t,n.logLevel??"info",g,[r],[g]),oe(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Tn(t.route.path,e.method,o),u=q.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=R.badRequest(e,t,{detail:g});return re(n.validateBody)&&ne(t,n.logLevel??"info",g,[r],[g]),oe(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=po(l),y=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(re(n.validateBody)&&ne(t,n.logLevel??"info",d,[r],p),oe(n.validateBody))return y}s(sa,"handleBodyValidation");function aa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ve(t),i=We(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(re(n.validateHeaders)&&ne(t,n.logLevel??"info",a,i.invalidValues,i.errors),oe(n.validateHeaders))return u}}s(aa,"handleHeadersValidation");function ua(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ve(t),o=We(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(re(n.validatePathParameters)&&ne(t,n.logLevel??"info",i,o.invalidValues,o.errors),oe(n.validatePathParameters))return a}}s(ua,"handlePathParameterValidation");function ca(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ve(t),o=We(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(re(n.validateQueryParameters)&&ne(t,n.logLevel??"info",i,o.invalidValues,o.errors),oe(n.validateQueryParameters))return a}}s(ca,"handleQueryParameterValidation");var mo=s(async(t,e,n)=>{let r=ca(e,t,n);if(r!==void 0||(r=ua(e,t,n),r!==void 0)||(r=aa(e,t,n),r!==void 0))return r;let o=await sa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),la=mo;var da=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new m(`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 pa=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var ma=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var ga=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`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 m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var fa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var ha=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 Ul=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ya=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ul(n.sleepInMs),t},"SleepInboundPolicy");var ba=s(async(t,e,n,r)=>{H(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await F(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 I(`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 wa=s(async(t,e,n,r)=>{H(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new Z(o,e),a=await i.get(r);if(!a){let u=await Hl(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 Hl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await V({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 I("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 I("Response returned from Azure AD is not in the expected format.")}s(Hl,"getAccessToken");var Ra="https://accounts.google.com/o/oauth2/token",go,Pa=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string"),go||(go=await K.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 $(r,n),a=new Z(i,e),u=await a.get(r);if(!u){let c=await se({serviceAccount:go,audience:Ra,payload:o}),l=await jt(Ra,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("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 Nl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Zl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],fo,Ia=s(async(t,e,n,r)=>{if(H(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new m(`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(Zl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}fo||(fo=await K.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("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 I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await $(r,n),u=new Z(a,e),c={uid:i,claims:o},l=await yn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await se({serviceAccount:fo,audience:Nl,payload:c}),y=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await vi(y,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new I("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var ho,Ea=s(async(t,e,n,r)=>{H(n,r).required("audience","string").required("serviceAccountJson","string"),ho||(ho=await K.init(n.serviceAccountJson));let o=await se({serviceAccount:ho,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var xa="https://www.googleapis.com/oauth2/v4/token",yo,va=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),yo||(yo=await K.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=ve(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await $(r,n),a;n.useMemoryCacheOnly?a=new Le(i):a=new Z(i,e);let u=await a.get(r);if(!u){let c=await se({serviceAccount:yo,audience:xa,payload:o}),l=await jt(xa,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new I("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new I("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Sa=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 On=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 bo=["sha-1","sha-256","sha-384","sha-512"],Cn=class{static{s(this,"BaseCryptoBeta")}};var An=class extends Cn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!bo.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${bo.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 Ln=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var _n=class extends Ln{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new wt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new m("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 ue(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(il,"validateComputedSignature");function sl(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(sl,"parseHeader");function al(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(al,"secureCompare");async function ul(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]=Jr[i[u]];return a.join("")}s(ul,"computeHMACSignatureAsync");var Jr=new Array(256);for(let t=0;t<Jr.length;t++)Jr[t]=t.toString(16).padStart(2,"0");function H(t,e){if(!Ee(t))throw new m(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new m(`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 m(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new m(`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 m(`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 m(`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(H,"optionValidator");var Be=class extends ee{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){H(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ss(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),R.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function as(t){return t!==null&&typeof t=="object"&&"id"in t&&W(t.id)&&"type"in t&&W(t.type)}s(as,"isStripeWebhookEvent");var gn=class extends ce{static{s(this,"MeteringPlugin")}};var cl={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 I(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 I(i)}return o}},us=cl;var Yr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function cs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${t}/consumers`,Yr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),y=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,y),new I(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(cs,"createConsumer");async function ls({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${t}/consumers`,Yr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await V({retryDelayMs:5,retries:2,logger:O.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let y="Error creating API Key Consumer";throw i.log.error(y,p),new I(y)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(ls,"createConsumerInvite");async function ds({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Yr);o.searchParams.set("with-api-key","true");let i=await V({retryDelayMs:5,retries:2,logger:O.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new I(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(ds,"deleteConsumer");async function ps({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=h.instance;if(!Me(l))throw new T("No Zuplo JWT token set.");let p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let y="Error creating metering subscription.",g;try{g=await p.json()}catch{g={status:p.status,statusText:p.statusText}}throw t.log.error(y,g),new I(y)}t.log.info("Successfully created/updated metering subscription.",c)}s(ps,"createSubscription");async function gt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Me(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new I(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(gt,"updateSubscription");async function ft({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Me(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new I(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}return u.data[0]}s(ft,"getSubscription");function fn(t){return t.replaceAll("_","-")}s(fn,"stripeStatusToMeteringStatus");async function Qr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await cs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await us.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ls({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return R.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=fn(n.data.object.status);await ps({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await ds({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),R.internalServerError(t,e,{detail:l.message})}return R.ok(t,e)}s(Qr,"onCustomerSubscriptionCreated");async function Xr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),R.ok(t,e)}s(Xr,"onCustomerSubscriptionDeleted");async function eo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=fn(n.data.object.status);return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),R.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[n.data.object.plan.product]}}),R.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),R.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(eo,"onCustomerSubscriptionUpdated");var to=class extends gn{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(z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let y=this.options.meteringBucketRegion??"us-central1";if(!ll(y))throw new m(`StripeMeteringPlugin - The value '${y}' on the property 'meteringBucketRegion' is invalid.`);let g=await c.json();if(!as(g))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 '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Qr(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await eo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Xr(c,l,g,{meteringBucketId:d});default:return R.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=gi({inboundPolicies:[new Be({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),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 ll(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(ll,"isMetricsRegion");var gs=new WeakMap,ms={},hn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){gs.set(e,n)}};async function fs(t,e,n,r){if(!n.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Mt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=gs.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(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)},y=ms[n.apiKey];if(!y){let g=n.apiKey,w=t.headers.get("zm-test-id")??"";y=new C("amberflo-ingest-meter",10,async P=>{try{let E=n.url??"https://app.amberflo.io/ingest",x=await fetch(E,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),ms[g]=y}y.enqueue(p),e.waitUntil(y.waitUntilFlushed())}}),t}s(fs,"AmberfloMeteringInboundPolicy");async function yn(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(yn,"sha256");var hs=new Map;async function $(t,e){let n,r=hs.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await yn(JSON.stringify({policyName:t,options:e}))}`,hs.set(t,n)),n}s($,"getPolicyCacheName");var ys="key-metadata-cache-type";function dl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(dl,"getKeyValue");async function bn(t,e,n,r){if(!n.bucketName)if(z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`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 m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(E=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:E}),"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=dl(a,o);if(!u||u==="")return i("No key present");let c=await pl(u),l=await $(r,o),d=new Z(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!==ys&&O.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let y={key:u},g=await V({retryDelayMs:5,retries:2,logger:O.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(y)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let E=await g.text(),x=JSON.parse(E);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let w=await g.json(),P={isValid:!0,typeId:ys,user:{sub:w.name,data:w.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(bn,"ApiKeyInboundPolicy");async function pl(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(pl,"hashValue");var bs=bn;var ht=require("jose");var no={},ml=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");no[e.jwkUrl]||(no[e.jwkUrl]=(0,ht.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ht.jwtVerify)(t,no[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),gl=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,ht.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),F=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(y=>R.unauthorized(t,e,{detail:y}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?ml:gl,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 y=o.substring(i.length);if(!y||y.length===0)return a("No bearer token on authorization header");try{return await u(y,n)}catch(g){let w=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,g),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 ws=s(async(t,e,n,r)=>F(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Rs=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 y=d.substring(0,p),g=d.substring(p+1),w=n.accounts.find(P=>P.username===y&&P.password===g);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 fl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function hl(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(hl,"digestMessage");var yl=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 hl(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 Ps(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await yl(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 y=n?.expirationSecondsTtl??60,g=new Response(p.body,p);fl.forEach(w=>g.headers.delete(w)),g.headers.set("cache-control",`s-maxage=${y}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ps,"CachingInboundPolicy");var Is=s(async(t,e,n,r)=>{if(!n.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Es=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 xs=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 vs=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",F(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 m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return F(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 Ts=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=q.instance,i=it(n.policies,o?.routeData.policies);return hr(i)(t,e)},"CompositeInboundPolicy");var Os=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=bl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(r,n),u=new Z(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 bl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(bl,"getToken");var Cs=s(async(t,e,n,r)=>(H(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),F(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 As=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 je="__unknown__",Ls=s(async(t,e,n,r)=>{let o={allow:{countries:Ge(n.allow?.countries,"allow.countries",r),regionCodes:Ge(n.allow?.regionCodes,"allow.regionCode",r),asns:Ge(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ge(n.block?.countries,"block.countries",r),regionCodes:Ge(n.block?.regionCodes,"block.regionCode",r),asns:Ge(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??je,a=e.incomingRequestProperties.regionCode?.toLowerCase()??je,u=e.incomingRequestProperties.asn?.toString()??je,c=o.ignoreUnknown&&i===je,l=o.ignoreUnknown&&a===je,d=o.ignoreUnknown&&u===je,p=o.allow.countries,y=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||y.length>0&&!y.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ze(t,e,r,i,a,u);let w=o.block.countries,P=o.block.regionCodes,E=o.block.asns;return w.length>0&&w.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ze(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(ze,"blockedResponse");function Ge(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 m(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ge,"toLowerStringArray");var _s=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");async function ks(t,e,n,r){let o=O.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=h.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(ks,"loadSubscription");async function Ds(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=h.instance,u=O.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(Ds,"consumeSubcriptionQuotas");var wl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function wn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new m(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(wn,"validateMeters");function Ms(t,e){if(t)try{if(t.length===0)throw new m("Must set valid subscription statuses");let n=ve(t),r=[];for(let o of n)wl.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(Ms,"parseAllowedSubscriptionStatuses");var Rn=class extends ee{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return X.get(e,Qe)}static setMeters(e,n){wn(n,"setMeters"),X.set(e,Pt,n)}async handler(e,n){if(H(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new m(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let r=this.options.allowRequestsOverQuota??!1,o=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:Mt(this.options.meterOnStatusCodes),i=X.get(n,Pt),a={...this.options.meters,...i};wn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ms(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(P,E,x)=>{let A=X.get(x,Qe);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){x.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(z.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let _=X.get(x,Pt),M={...this.options.meters,..._};wn(M,this.policyName),o.includes(P.status)&&A&&M&&(x.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(M)} on response status '${P.status}'`),await Ds(x,A.id,this.policyName,this.options.bucketId,M))});let l=e.user;if(!l)return u?e:R.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(z.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ks(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:R.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),R.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),X.set(n,Qe,p));let y=X.get(n,Qe);if(!y)return u?e:(n.log.warn("Subscription is not available for user"),R.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(y&&Object.keys(y.meters).length===0)return n.log.error(`Quota is not set up for subscription '${y.id}'`),R.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let w=Object.keys(a).filter(P=>!Object.keys(y.meters).includes(P));if(w.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${w.join(", ")}`),R.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${w.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(y.meters[P].consumed<=0&&!r)return R.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Hs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return ro(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 ro(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(y=>{a.push({responseName:u,contentName:l,exampleName:y,exampleValue:d[y]})})})}),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 Us(a[u])}else return a.length>0?Us(a[0]):ro(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 Us(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(Us,"generateResponse");var ro=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",Pl={logRequestBody:!0,logResponseBody:!0};function Ns(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ns,"headersToObject");function Zs(){return new Date().toISOString()}s(Zs,"timestamp");var oo=new WeakMap,Il={};function Fs(t,e){let n=oo.get(t);n||(n=Il);let r=Object.assign({...n},e);oo.set(t,r)}s(Fs,"setMoesifContext");async function qs(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(qs,"readBody");var El={},io;function $s(){if(!io)throw new I("Invalid State - no _lastLogger");return io}s($s,"getLastLogger");function xl(t){let e=El[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);$s().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||$s().error({status:o.status,body:await o.text()})})),e}s(xl,"getDispatcher");async function Bs(t,e,n,r){io=e.log;let o=Zs(),i=Object.assign(Pl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await qs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=xl(i.applicationId),d=t.headers.get("true-client-ip"),p=oo.get(e)??{},y={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ns(t.headers)},g=i.logResponseBody?await qs(u,e):void 0,w={time:Zs(),status:u.status,headers:Ns(u.headers),body:g},P={request:y,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Rl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(Bs,"MoesifInboundPolicy");var js=s(async(t,e,n,r)=>F(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var zs=require("jose");var so,Gs=s(async(t,e,n,r)=>{if(!so)try{so=await(0,zs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:so,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ws=Ae(Pe());var Pn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ao=class extends Pn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},uo=class extends Pn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function vl(t,e){if(ui(t))throw new ao(e)}s(vl,"throwIfUndefinedOrNull");function yt(t,e){if(vl(t,e),!W(t))throw new uo(e,"string")}s(yt,"throwIfNotString");var In=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 yt(e,"redisClientUrl"),yt(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}){yt(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)}`)}},En=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(yt(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 xn=(0,Ws.debug)("zuplo:policies:RateLimitInboundPolicy"),Sl="strict",Tl=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"),Ol=s(async t=>({key:`ip-${Tl(t)}`}),"getIP"),Cl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Al=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),vn;function Ll(t,e){let n;if(vn)return vn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new En,vn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!W(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!W(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=In.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return vn=n,n}s(Ll,"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 _l(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new m(`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 m(`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 I(c)}return u},"outerFunction")}s(_l,"wrapUserFunction");var kl="Retry-After",co=s(async(t,e,n,r)=>{let o=Date.now(),i=O.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[kl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:_l(n,r),user:Cl,ip:Ol,all:Al}[n.rateLimitBy],d=await l(t,e,r),p=d.key,y=d.requestsAllowed??n.requestsAllowed,g=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",P=Ll(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Sl)==="async"){let _=await $(r,n),M=new de(_,{logger:O.getLogger(e)}),Y=Vs(x,g,P,i,e.requestId),Q=await M.get(x);if(Q!==void 0&&Q<=Date.now()){xn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Oe=Math.round((Q-Date.now())/1e3);return u(w,Oe)}return e.addEventListener("responseSending",Oe=>{try{let Ce=Oe,kn=Ce.mutableResponse;Ce.mutableResponse=(async()=>{let bt=await Y;if(bt.count>y){let Ta=Date.now()+bt.ttlSeconds*1e3,Oa=M.put(x,Ta,bt.ttlSeconds).catch(wo=>{throw i.error(new T("Error caching rate limit result.",{cause:wo})),wo});return e.waitUntil(Oa),xn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,bt.ttlSeconds)}return kn})()}catch(Ce){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ce)}}),t}let N=await Vs(x,g,P,i,e.requestId);return N.count>y?(xn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,N.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;xn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var lo;function Ks(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ks,"headersToNameValuePairs");function Dl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Dl,"queryToNameValueParis");function Ml(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Ml,"parseIntOrUndefined");var Js={};async function Ys(t,e,n,r){let o=new Date,i=Date.now();return lo||(lo={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:lo,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:Ks(t.headers),queryString:Dl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ks(a.headers),content:{size:Ml(t.headers.get("content-length"))}}}]}}},d=Js[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async y=>{try{let g=n.url??"https://metrics.readme.io/request",w=await fetch(g,{method:"POST",body:JSON.stringify(y),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(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Js[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Ys,"ReadmeMetricsInboundPolicy");var Qs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Xs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`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 ea=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ta=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 na=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ra=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?na():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?na():t},"RequestSizeLimitInboundPolicy");function oa(t,e,n){return`_${we(t+"_"+e+"_"+n)}`}s(oa,"getRawOperationDataIdentifierName");function Sn(t,e,n,r){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(Sn,"getIdForParameterSchema");function Tn(t,e,n){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${we(n.toLowerCase())}`}s(Tn,"getIdForRequestBodySchema");function ia(t,e){return`_${we(t)}__${we(e)}`}s(ia,"getIdForRefSchema");function we(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(we,"sanitizedIdentifierName");var Ve=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"),We=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=Sn(n,r,o,c.name),p=q.instance.schemaValidator[d],y=p(e[c.name]),g=po(p.errors);y||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ne=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),re=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),oe=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),po=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 sa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=R.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${g}`});if(re(n.validateBody)&&ne(t,n.logLevel??"info",w,[r],g),oe(n.validateBody))return P}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=R.badRequest(e,t,{detail:g});return re(n.validateBody)&&ne(t,n.logLevel??"info",g,[r],[g]),oe(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Tn(t.route.path,e.method,o),u=q.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=R.badRequest(e,t,{detail:g});return re(n.validateBody)&&ne(t,n.logLevel??"info",g,[r],[g]),oe(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=po(l),y=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(re(n.validateBody)&&ne(t,n.logLevel??"info",d,[r],p),oe(n.validateBody))return y}s(sa,"handleBodyValidation");function aa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ve(t),i=We(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(re(n.validateHeaders)&&ne(t,n.logLevel??"info",a,i.invalidValues,i.errors),oe(n.validateHeaders))return u}}s(aa,"handleHeadersValidation");function ua(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ve(t),o=We(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(re(n.validatePathParameters)&&ne(t,n.logLevel??"info",i,o.invalidValues,o.errors),oe(n.validatePathParameters))return a}}s(ua,"handlePathParameterValidation");function ca(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ve(t),o=We(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(re(n.validateQueryParameters)&&ne(t,n.logLevel??"info",i,o.invalidValues,o.errors),oe(n.validateQueryParameters))return a}}s(ca,"handleQueryParameterValidation");var mo=s(async(t,e,n)=>{let r=ca(e,t,n);if(r!==void 0||(r=ua(e,t,n),r!==void 0)||(r=aa(e,t,n),r!==void 0))return r;let o=await sa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),la=mo;var da=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new m(`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 pa=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var ma=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var ga=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`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 m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var fa=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var ha=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 Ul=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ya=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ul(n.sleepInMs),t},"SleepInboundPolicy");var ba=s(async(t,e,n,r)=>{H(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await F(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 I(`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 wa=s(async(t,e,n,r)=>{H(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new Z(o,e),a=await i.get(r);if(!a){let u=await Hl(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 Hl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await V({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 I("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 I("Response returned from Azure AD is not in the expected format.")}s(Hl,"getAccessToken");var Ra="https://accounts.google.com/o/oauth2/token",go,Pa=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string"),go||(go=await K.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 $(r,n),a=new Z(i,e),u=await a.get(r);if(!u){let c=await se({serviceAccount:go,audience:Ra,payload:o}),l=await jt(Ra,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("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 Nl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Zl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],fo,Ia=s(async(t,e,n,r)=>{if(H(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new m(`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(Zl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}fo||(fo=await K.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("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 I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await $(r,n),u=new Z(a,e),c={uid:i,claims:o},l=await yn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await se({serviceAccount:fo,audience:Nl,payload:c}),y=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await vi(y,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new I("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var ho,Ea=s(async(t,e,n,r)=>{H(n,r).required("audience","string").required("serviceAccountJson","string"),ho||(ho=await K.init(n.serviceAccountJson));let o=await se({serviceAccount:ho,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var xa="https://www.googleapis.com/oauth2/v4/token",yo,va=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),yo||(yo=await K.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=ve(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await $(r,n),a;n.useMemoryCacheOnly?a=new Le(i):a=new Z(i,e);let u=await a.get(r);if(!u){let c=await se({serviceAccount:yo,audience:xa,payload:o}),l=await jt(xa,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new I("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new I("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Sa=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 On=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 bo=["sha-1","sha-256","sha-384","sha-512"],Cn=class{static{s(this,"BaseCryptoBeta")}};var An=class extends Cn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!bo.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${bo.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 Ln=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var _n=class extends Ln{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new wt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new m("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 */
|