@zuplo/runtime 5.2420.0 → 5.2422.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/cjs/index.js CHANGED
@@ -32,7 +32,7 @@
32
32
  `))):u=n.stylize("[Circular]","special")),Xi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Br,"formatProperty");function Dl(n,e){if(Xi(e))return n.stylize("undefined","undefined");if(es(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Ll(e))return n.stylize(""+e,"number");if(Al(e))return n.stylize(""+e,"boolean");if(ts(e))return n.stylize("null","null")}i(Dl,"formatPrimitive");function Ml(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
34
  `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Ml,"reduceToSingleString")});var os=Bt(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.format=void 0;var Ul=Qi(),ql=rs(),Zl=i((n,...e)=>(0,Ul.format)(ql.inspect,n,e),"format");hn.format=Zl});var He=Bt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var Hl=Ji(),Fl=os(),yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,Fl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=yn;var bn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function is(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(is,"extract");var Gt;function $l(n){n||(n=[]),typeof n=="string"&&(n=is(n)),Gt=new bn(n)}i($l,"withoutEnv");Ve.withoutEnv=$l;function jl(n){let e=globalThis.DEBUG;Gt||(Gt=new bn(is(e)));let t=new yn(Gt,n);return Gt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(jl,"debug");Ve.debug=jl});var im={};Mc(im,{AWSLoggingPlugin:()=>rr,AmberfloMeteringInboundPolicy:()=>eu,AmberfloMeteringPolicy:()=>lr,ApiAuthKeyInboundPolicy:()=>ru,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>sr,AuditLogPlugin:()=>ar,Auth0JwtInboundPolicy:()=>su,AwsLambdaHandlerExtensions:()=>Na,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>au,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>ee,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>cu,ChangeMethodInboundPolicy:()=>lu,ClearHeadersInboundPolicy:()=>pu,ClearHeadersOutboundPolicy:()=>mu,ClerkJwtInboundPolicy:()=>gu,CognitoJwtInboundPolicy:()=>fu,ComplexRateLimitInboundPolicy:()=>Rr,CompositeInboundPolicy:()=>bu,ConfigurationError:()=>f,ContentTypes:()=>xn,ContextData:()=>ue,CryptoBeta:()=>Dr,CurityPhantomTokenInboundPolicy:()=>wu,DataDogLoggingPlugin:()=>zn,DataDogMetricsPlugin:()=>or,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>ir,FirebaseJwtInboundPolicy:()=>Ru,FormDataToJsonInboundPolicy:()=>Pu,GeoFilterInboundPolicy:()=>Iu,GoogleCloudLoggingPlugin:()=>Fn,Handler:()=>Qn,HttpProblems:()=>x,HttpStatusCode:()=>Yt,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Eu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>er,LookupResult:()=>xt,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>xu,MoesifInboundPolicy:()=>_u,MonetizationInboundPolicy:()=>Ir,OktaFGAAuthZInboundPolicy:()=>xr,OktaJwtInboundPolicy:()=>Hu,OpenFGAAuthZInboundPolicy:()=>Or,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>$u,QuotaInboundPolicy:()=>wr,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Ju,RemoveHeadersInboundPolicy:()=>Qu,RemoveHeadersOutboundPolicy:()=>Yu,RemoveQueryParamsInboundPolicy:()=>Xu,ReplaceStringOutboundPolicy:()=>ec,RequestSizeLimitInboundPolicy:()=>nc,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>lc,ResponseSendingEvent:()=>Rt,ResponseSentEvent:()=>Pt,Router:()=>Ot,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Kt,SchemaBasedRequestValidation:()=>cc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>dc,SetHeadersInboundPolicy:()=>pc,SetHeadersOutboundPolicy:()=>mc,SetQueryParamsInboundPolicy:()=>gc,SetStatusOutboundPolicy:()=>fc,SleepInboundPolicy:()=>hc,StripeMonetizationPlugin:()=>gi,StripeWebhookVerificationInboundPolicy:()=>At,SumoLogicLoggingPlugin:()=>tr,SupabaseJwtInboundPolicy:()=>yc,SystemRouteName:()=>Me,TelemetryPlugin:()=>bt,UpstreamAzureAdServiceAuthInboundPolicy:()=>bc,UpstreamFirebaseAdminAuthInboundPolicy:()=>Rc,UpstreamFirebaseUserAuthInboundPolicy:()=>Pc,UpstreamGcpFederatedAuthInboundPolicy:()=>Sr,UpstreamGcpJwtInboundPolicy:()=>Tc,UpstreamGcpServiceAuthInboundPolicy:()=>Oc,VMWareLogInsightLoggingPlugin:()=>nr,ValidateJsonSchemaInbound:()=>vc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>yt,ZuploRequest:()=>oe,ZuploServices:()=>jt,awsLambdaHandler:()=>Da,environment:()=>Ee,getIdForParameterSchema:()=>vr,getIdForRefSchema:()=>oc,getIdForRequestBodySchema:()=>Cr,getRawOperationDataIdentifierName:()=>rc,httpStatuses:()=>Cn,openApiSpecHandler:()=>Ma,redirectHandler:()=>Ua,sanitizedIdentifierName:()=>it,serialize:()=>On,setMoesifContext:()=>Au,trackFeature:()=>y,urlForwardHandler:()=>qa,urlRewriteHandler:()=>Za,webSocketHandler:()=>Ha,webSocketPipelineHandler:()=>ja});module.exports=Uc(im);var ds=Be(He());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},wn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};function zl(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<n.length;l++){let d=n.charAt(l),p=d.charCodeAt(0);if(e[p]!==255)throw new TypeError(d+" is ambiguous");e[p]=l}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function a(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let d=0,p=0,g=0,h=l.length;for(;g!==h&&l[g]===0;)g++,d++;let v=(h-g)*s+1>>>0,b=new Uint8Array(v);for(;g!==h;){let A=l[g],$=0;for(let N=v-1;(A!==0||$<p)&&N!==-1;N--,$++)A+=256*b[N]>>>0,b[N]=A%t>>>0,A=A/t>>>0;if(A!==0)throw new Error("Non-zero carry");p=$,g++}let I=v-p;for(;I!==v&&b[I]===0;)I++;let D=r.repeat(d);for(;I<v;++I)D+=n.charAt(b[I]);return D}i(a,"encode");function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let d=0,p=0,g=0;for(;l[d]===r;)p++,d++;let h=(l.length-d)*o+1>>>0,v=new Uint8Array(h);for(;l[d];){let A=e[l.charCodeAt(d)];if(A===255)return;let $=0;for(let N=h-1;(A!==0||$<g)&&N!==-1;N--,$++)A+=t*v[N]>>>0,v[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=$,d++}let b=h-g;for(;b!==h&&v[b]===0;)b++;let I=new Uint8Array(p+(h-b)),D=p;for(;b!==h;)I[D++]=v[b++];return I}i(u,"decodeUnsafe");function c(l){let d=u(l);if(d)return d;throw new Error("Non-base"+t+" character")}return i(c,"decode"),{encode:a,decodeUnsafe:u,decode:c}}i(zl,"base");var ss=zl;var Bl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",as=ss(Bl);var Wr="2024-03-14",us=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function cs(){return new m({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Wr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:us[Wr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(cs,"getMockEnvironment");var m=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=cs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}if(t.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(as.decode(t.ZUPLO_SYSTEM_CONFIGURATIONS)),s=JSON.parse(o);for(let a of Object.keys(s))t[a]=s[a]}}catch(o){console.error("Failed to parse runtime configuration",o)}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var at=(0,ds.debug)("zuplo:runtime:external-service");function Gl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=m.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Gl,"getServiceAuth");async function ps(n,e){let t=Gl();if(t)if(at(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(m.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{at("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Vl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);at(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ps,"externalServiceHandler");async function Vl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wl(r);at(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ls(`${s}-${o}`),l=await ls(`${s}-${a}-${u}`);return`${c}.${l}`}i(Vl,"hashServiceName");async function ls(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(ls,"hashSegment");function Wl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wl,"sanitizeEnvironmentType");var gs=new Map;gs.set("service:",ps);var ms=globalThis.fetch;function Kr(n,e){let t=Kl(e);if(typeof n=="string"){let r=new URL(n),o=gs.get(r.protocol);return o?o(n,t):ms(n,t)}else return ms(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Kl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Jl={fetch:Kr},F=Jl;Function.prototype.toString=function(){return"[native code]"};var Rn=globalThis,fs=Rn.caches;if(fs){let n=fs.open;Rn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Rn.caches.default,Object.freeze(Rn.caches)}var hs=new Map,Jr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},We=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=hs.get(e);r||(r=new Jr(t),hs.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Qr="__zuplo-expiry-header",yt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(Qr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Qr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Qr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var se=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new yt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var ys="zuplo-request-id",ut="zp-rid",Yr="zp-body-removed",ct="cf-ray",bs="x-real-ip",Xr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ws="cf-region",Rs="cf-region-code",Ps="cf-metro-code",Is="cf-postal-code",Es="cf-timezone",Ts="zp-ipcity",xs="zp-ipcontinent",Os="zp-ipcountry",vs="zp-iplongitude",Cs="zp-iplatitude",Ss="true-client-ip",oo="zp-asn",io="zp-asorg",so="zp-colo",ao="zp-postalcode",uo="zp-metrocode",co="zp-region",lo="zp-regioncode",po="zp-timezone",As=[Xr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],_s=["zp-","cf-"],Ls=[ut,ct,Yr];var Vt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var wa=require("@opentelemetry/api"),Ra=Be(He());var vn=require("@opentelemetry/api");var Qe=require("@opentelemetry/api");var ks=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ns(n){ks=n}i(Ns,"setTelemetryInitFunction");var Ds=i(n=>ks(n),"proxyHandler");var Ke=class{static{i(this,"RuntimePlugin")}},Fe=class extends Ke{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Pn=class extends Fe{static{i(this,"MeteringPlugin")}},bt=class extends Ke{static{i(this,"TelemetryPlugin")}};var In=new Set,Ms=new Set;function y(n){Ms.has(n)||(Ms.add(n),In.add(n))}i(y,"trackFeature");function Us(){let n=[...In];return In.clear(),n}i(Us,"getUnsentFeatures");function qs(n){for(let e of n)In.add(e)}i(qs,"restoreFeatures");var Jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Je=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Jt.problemResponseFormat(e,t,r)}};function En(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&En(t)}return Object.freeze(n)}i(En,"deepFreeze");var oe=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return En(this.#e)}get params(){return En(this.#t)}user};var Qt={},$e=[],mo=[],go=[],fo=[];var Tn={addPlugin(n){$e.push(n)},addRequestHook(n){mo.push(n)},addResponseSendingHook(n){go.push(n)},addResponseSendingFinalHook(n){fo.push(n)}},Hs=i(async(n,e)=>{if(mo.length===0)return n;let t=Qe.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of mo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof oe||c instanceof Response)return u.end(),c;{let l=new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Qe.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Fs=i(async(n,e,t)=>{if(go.length===0)return n;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of go)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Qe.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),$s=i(async(n,e,t)=>{if(fo.length===0)return;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of fo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Qe.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Zs=!1;async function js(n){if(!Zs){n&&(y("runtime.extensions"),await n(Tn)),Qt.value=Tn;for(let e of $e)if(e instanceof bt){let{requestHandlerProxy:t}=e.instrument({accountName:m.instance.build.ACCOUNT_NAME,projectName:m.instance.build.PROJECT_NAME,buildId:m.instance.build.BUILD_ID,zuploVersion:m.instance.build.ZUPLO_VERSION,compatibilityDate:m.instance.build.COMPATIBILITY_DATE,instanceId:m.instance.instanceId,environmentType:m.instance.loggingEnvironmentType,environmentStage:m.instance.loggingEnvironmentStage,deploymentName:m.instance.deploymentName});Ns(t)}for(let e of $e)e instanceof Fe&&await e.initialize(Tn);Jt.setProblemResponseFormat(Tn.problemResponseFormat),Zs=!0}}i(js,"initializeRuntime");var xn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function On(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(xn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(xn.Json)||!e?JSON.stringify(n):n}i(On,"serialize");function wt(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(wt,"isSystemRoute");var he=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>vn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:vn.SpanStatusCode.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let I=a.pop();return I?I(o,s,t,u):await this.#e(async $=>{let N=await r($,s);return Ql(N)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(wt(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Rt(o,l);s.dispatchEvent(p);let g=Pe.getContextExtensions(s),h=g.latestRequest,v;try{v=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{v=await g.onResponseSending(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{v=await Fs(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new Pt(o,v));try{await g.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await $s(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return v},"#toZuploPipeline")};function Ql(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(On(n),{headers:{"content-type":"application/json"}})}i(Ql,"resultToResponse");var Yt=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Yt||{}),zs={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 Yl={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"},Cn=Yl;function Xl(n){return`${new URL(n.url).pathname}`}i(Xl,"instance");function ed(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(ct);return r&&(t.rayId=r),t}i(ed,"trace");var td=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Xl(e),trace:ed(e,t),...r},additionalHeaders:o,statusText:Cn[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:zs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=td(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var Ye=class extends Ke{static{i(this,"MetricsPlugin")}};var te=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new Q(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ee=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new ee("ellie-metrics-transport",10,this.dispatchFunction,te.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=m.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=m.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Us(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":m.instance.deploymentName??"unknown","user-agent":m.instance.systemUserAgent}});if(!l.ok){let d=await l.text();te.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),qs(u)}},"dispatchFunction")};var pe=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Xt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Xt={name:"__system-no-version",pathPrefix:""};var Ie=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ct)??void 0,c=n.headers.get(Ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Sn(e)),$e.forEach(v=>{if(v instanceof Ye){let b=v.getTransport();h.push(b)}}),h.forEach(v=>{v.pushMetrics(g,e)}),a},"metricsProcessor");var Me=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(Me||{});var yo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=m.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new he({processors:[Ie],handler:t,gateway:e}),o=new pe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:nd}=Object.prototype,{propertyIsEnumerable:rd}=Object.prototype;function bo(n){return nd.call(n)}i(bo,"toString");function Oe(n){return typeof n=="string"}i(Oe,"isString");function It(n){return Oe(n)&&n!==""}i(It,"isNonEmptyString");function Bs(n){return bo(n)==="[object RegExp]"}i(Bs,"isRegexp");function Gs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>rd.call(n,e))]}i(Gs,"getOwnEnumerableKeys");function lt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(lt,"isObject");function wo(n){return typeof n=="number"&&!isNaN(n)}i(wo,"isNumber");function Ro(n){return n===!0||n===!1}i(Ro,"isBoolean");function Vs(n){return typeof n>"u"}i(Vs,"isUndefined");function Ws(n){return Vs(n)||n===null}i(Ws,"isUndefinedOrNull");function en(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(en,"isErrorLike");var Ks=new Map;function Xe(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Ks.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ks.set(n,r),r}i(Xe,"statusCodesStringToNumberArray");function dt(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(dt,"getValueFromRequestUser");function pt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("Received an array that contains non-string values.");return n}if(Oe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new f(`Expected type of string, received type '${typeof n}'`)}i(pt,"parseValueToStringArray");function Js(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!lt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!It(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Ro(t.allowCredentials))throw new f("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=Po(t,"allowedHeaders"),o=Po(t,"allowedMethods"),s=Po(t,"exposeHeaders"),a;try{a=pt(t.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Js,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=pt(n[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Po,"parseOptionalProperty");var An=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),_n=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var Io=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return x.notFound(a,u);let h=g.routeConfiguration,v=od(l,d,p,h,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),x.notFound(a,u))},"optionsHandler"),o=new he({processors:[Ie],handler:r,gateway:e}),s=new pe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),od=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=An(a.allowedOrigins,t);return u?{isValid:!0,headers:_n(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Qs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new he({processors:[Ie],handler:t,gateway:e}),o=new pe({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Eo=new pe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ys=i((n,e)=>{let t=i(async(o,s)=>{let a=Qt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var id=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xs=i(n=>{id.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Xs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=sd(o,t.routeData.corsPolicies),u=ad(n,a),c=new Headers(s.headers);return Xs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),sd=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ad=i((n,e)=>{let t=An(e.allowedOrigins,n.headers.get("origin"));return t?_n(e,t):{}},"getCorsHeaders");var To=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:m.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new he({processors:[Ln],handler:t,gateway:e}),o=new pe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var Et=require("@opentelemetry/api");var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var kn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Oe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},le=class extends kn{static{i(this,"InboundPolicy")}},je=class extends kn{static{i(this,"OutboundPolicy")}};var vo=class extends le{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Co=class extends je{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},xo=new Map;function tn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!xo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new f(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof le)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new vo(u,a.handler.options,a.name);else throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new f(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);xo.set(a.name,c)}),t.map(s=>{let a=xo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(tn,"getInboundPolicyInstances");var Oo=new Map;function ud(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Oo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new f(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof je)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Co(a,s.handler.options??{},s.name);else throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Oo.set(s.name,u)}),t.map(o=>{let s=Oo.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(ud,"getOutboundPolicyInstances");var So=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof oe||p instanceof Response)return d.end(),p;{let g=new f(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Et.SpanStatusCode.ERROR}),d.recordException(g),g}});if(l instanceof oe)u=l;else if(l instanceof Request)u=new oe(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),cd=i(n=>async(e,t,r)=>{let o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let g=new f(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Et.SpanStatusCode.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Nn=i(async(n,e,t,r)=>{let o=tn(e.route,t.routeData.policies),s=ud(e.route,t.routeData.policies);return ta({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ea({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ta({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ea,"createInternalPolicyProcessor");async function ta({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=So(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=cd(r),d;return m.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(ta,"executePolicyProcessor");function na(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ld,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=dd(l,o)}s=u+1}return t}i(na,"parse");function ld(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ld,"decode");function dd(n,e){try{return e(n)}catch{return n}}i(dd,"tryDecode");function ra(n,e){try{let t=/v\d+(-\d+)?/g,o=na(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ra,"devPortalBaseURL");var oa="/__zuplo/dev-portal",pd="dev-portal-id",md="dev-portal-host",gd="zp-account",fd="zp-project",hd="dev-portal-build",yd=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Ml,"reduceToSingleString")});var os=Bt(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.format=void 0;var Ul=Qi(),ql=rs(),Zl=i((n,...e)=>(0,Ul.format)(ql.inspect,n,e),"format");hn.format=Zl});var He=Bt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var Hl=Ji(),Fl=os(),yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,Fl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=yn;var bn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function is(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(is,"extract");var Gt;function $l(n){n||(n=[]),typeof n=="string"&&(n=is(n)),Gt=new bn(n)}i($l,"withoutEnv");Ve.withoutEnv=$l;function jl(n){let e=globalThis.DEBUG;Gt||(Gt=new bn(is(e)));let t=new yn(Gt,n);return Gt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(jl,"debug");Ve.debug=jl});var im={};Mc(im,{AWSLoggingPlugin:()=>rr,AmberfloMeteringInboundPolicy:()=>eu,AmberfloMeteringPolicy:()=>lr,ApiAuthKeyInboundPolicy:()=>ru,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>sr,AuditLogPlugin:()=>ar,Auth0JwtInboundPolicy:()=>su,AwsLambdaHandlerExtensions:()=>Na,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>au,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>ee,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>cu,ChangeMethodInboundPolicy:()=>lu,ClearHeadersInboundPolicy:()=>pu,ClearHeadersOutboundPolicy:()=>mu,ClerkJwtInboundPolicy:()=>gu,CognitoJwtInboundPolicy:()=>fu,ComplexRateLimitInboundPolicy:()=>Rr,CompositeInboundPolicy:()=>bu,ConfigurationError:()=>f,ContentTypes:()=>xn,ContextData:()=>ue,CryptoBeta:()=>Dr,CurityPhantomTokenInboundPolicy:()=>wu,DataDogLoggingPlugin:()=>zn,DataDogMetricsPlugin:()=>or,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>ir,FirebaseJwtInboundPolicy:()=>Ru,FormDataToJsonInboundPolicy:()=>Pu,GeoFilterInboundPolicy:()=>Iu,GoogleCloudLoggingPlugin:()=>Fn,Handler:()=>Qn,HttpProblems:()=>x,HttpStatusCode:()=>Yt,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Eu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>er,LookupResult:()=>xt,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>xu,MoesifInboundPolicy:()=>_u,MonetizationInboundPolicy:()=>Ir,OktaFGAAuthZInboundPolicy:()=>xr,OktaJwtInboundPolicy:()=>Hu,OpenFGAAuthZInboundPolicy:()=>Or,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>$u,QuotaInboundPolicy:()=>wr,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Ju,RemoveHeadersInboundPolicy:()=>Qu,RemoveHeadersOutboundPolicy:()=>Yu,RemoveQueryParamsInboundPolicy:()=>Xu,ReplaceStringOutboundPolicy:()=>ec,RequestSizeLimitInboundPolicy:()=>nc,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>lc,ResponseSendingEvent:()=>Rt,ResponseSentEvent:()=>Pt,Router:()=>Ot,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Kt,SchemaBasedRequestValidation:()=>cc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>dc,SetHeadersInboundPolicy:()=>pc,SetHeadersOutboundPolicy:()=>mc,SetQueryParamsInboundPolicy:()=>gc,SetStatusOutboundPolicy:()=>fc,SleepInboundPolicy:()=>hc,StripeMonetizationPlugin:()=>gi,StripeWebhookVerificationInboundPolicy:()=>At,SumoLogicLoggingPlugin:()=>tr,SupabaseJwtInboundPolicy:()=>yc,SystemRouteName:()=>Me,TelemetryPlugin:()=>bt,UpstreamAzureAdServiceAuthInboundPolicy:()=>bc,UpstreamFirebaseAdminAuthInboundPolicy:()=>Rc,UpstreamFirebaseUserAuthInboundPolicy:()=>Pc,UpstreamGcpFederatedAuthInboundPolicy:()=>Sr,UpstreamGcpJwtInboundPolicy:()=>Tc,UpstreamGcpServiceAuthInboundPolicy:()=>Oc,VMWareLogInsightLoggingPlugin:()=>nr,ValidateJsonSchemaInbound:()=>vc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>yt,ZuploRequest:()=>oe,ZuploServices:()=>jt,awsLambdaHandler:()=>Da,environment:()=>Ee,getIdForParameterSchema:()=>vr,getIdForRefSchema:()=>oc,getIdForRequestBodySchema:()=>Cr,getRawOperationDataIdentifierName:()=>rc,httpStatuses:()=>Cn,openApiSpecHandler:()=>Ma,redirectHandler:()=>Ua,sanitizedIdentifierName:()=>it,serialize:()=>On,setMoesifContext:()=>Au,trackFeature:()=>y,urlForwardHandler:()=>qa,urlRewriteHandler:()=>Za,webSocketHandler:()=>Ha,webSocketPipelineHandler:()=>ja});module.exports=Uc(im);var ds=Be(He());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},wn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};function zl(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<n.length;l++){let d=n.charAt(l),p=d.charCodeAt(0);if(e[p]!==255)throw new TypeError(d+" is ambiguous");e[p]=l}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function a(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let d=0,p=0,g=0,h=l.length;for(;g!==h&&l[g]===0;)g++,d++;let v=(h-g)*s+1>>>0,b=new Uint8Array(v);for(;g!==h;){let A=l[g],$=0;for(let N=v-1;(A!==0||$<p)&&N!==-1;N--,$++)A+=256*b[N]>>>0,b[N]=A%t>>>0,A=A/t>>>0;if(A!==0)throw new Error("Non-zero carry");p=$,g++}let I=v-p;for(;I!==v&&b[I]===0;)I++;let D=r.repeat(d);for(;I<v;++I)D+=n.charAt(b[I]);return D}i(a,"encode");function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let d=0,p=0,g=0;for(;l[d]===r;)p++,d++;let h=(l.length-d)*o+1>>>0,v=new Uint8Array(h);for(;l[d];){let A=e[l.charCodeAt(d)];if(A===255)return;let $=0;for(let N=h-1;(A!==0||$<g)&&N!==-1;N--,$++)A+=t*v[N]>>>0,v[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=$,d++}let b=h-g;for(;b!==h&&v[b]===0;)b++;let I=new Uint8Array(p+(h-b)),D=p;for(;b!==h;)I[D++]=v[b++];return I}i(u,"decodeUnsafe");function c(l){let d=u(l);if(d)return d;throw new Error("Non-base"+t+" character")}return i(c,"decode"),{encode:a,decodeUnsafe:u,decode:c}}i(zl,"base");var ss=zl;var Bl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",as=ss(Bl);var Wr="2024-03-14",us=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function cs(){return new m({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Wr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:us[Wr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(cs,"getMockEnvironment");var m=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=cs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}if(t.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(as.decode(t.ZUPLO_SYSTEM_CONFIGURATIONS)),s=JSON.parse(o);for(let a of Object.keys(s))t[a]=s[a]}}catch(o){console.error("Failed to parse runtime configuration",o)}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var at=(0,ds.debug)("zuplo:runtime:external-service");function Gl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=m.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Gl,"getServiceAuth");async function ps(n,e){let t=Gl();if(t)if(at(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(m.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{at("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Vl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);at(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ps,"externalServiceHandler");async function Vl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wl(r);at(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ls(`${s}-${o}`),l=await ls(`${s}-${a}-${u}`);return`${c}.${l}`}i(Vl,"hashServiceName");async function ls(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(ls,"hashSegment");function Wl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wl,"sanitizeEnvironmentType");var gs=new Map;gs.set("service:",ps);var ms=globalThis.fetch;function Kr(n,e){let t=Kl(e);if(typeof n=="string"){let r=new URL(n),o=gs.get(r.protocol);return o?o(n,t):ms(n,t)}else return ms(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Kl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Jl={fetch:Kr},F=Jl;Function.prototype.toString=function(){return"[native code]"};var Rn=globalThis,fs=Rn.caches;if(fs){let n=fs.open;Rn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Rn.caches.default,Object.freeze(Rn.caches)}var hs=new Map,Jr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},We=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=hs.get(e);r||(r=new Jr(t),hs.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Qr="__zuplo-expiry-header",yt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(Qr);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Qr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Qr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var se=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new yt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var ys="zuplo-request-id",ut="zp-rid",Yr="zp-body-removed",ct="cf-ray",bs="x-real-ip",Xr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ws="cf-region",Rs="cf-region-code",Ps="cf-metro-code",Is="cf-postal-code",Es="cf-timezone",Ts="zp-ipcity",xs="zp-ipcontinent",Os="zp-ipcountry",vs="zp-iplongitude",Cs="zp-iplatitude",Ss="true-client-ip",oo="zp-asn",io="zp-asorg",so="zp-colo",ao="zp-postalcode",uo="zp-metrocode",co="zp-region",lo="zp-regioncode",po="zp-timezone",As=[Xr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],_s=["zp-","cf-"],Ls=[ut,ct,Yr];var Vt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var wa=require("@opentelemetry/api"),Ra=Be(He());var vn=require("@opentelemetry/api");var Qe=require("@opentelemetry/api");var ks=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ns(n){ks=n}i(Ns,"setTelemetryInitFunction");var Ds=i(n=>ks(n),"proxyHandler");var Ke=class{static{i(this,"RuntimePlugin")}},Fe=class extends Ke{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Pn=class extends Fe{static{i(this,"MeteringPlugin")}},bt=class extends Ke{static{i(this,"TelemetryPlugin")}};var In=new Set,Ms=new Set;function y(n){Ms.has(n)||(Ms.add(n),In.add(n))}i(y,"trackFeature");function Us(){let n=[...In];return In.clear(),n}i(Us,"getUnsentFeatures");function qs(n){for(let e of n)In.add(e)}i(qs,"restoreFeatures");var Jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Je=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Jt.problemResponseFormat(e,t,r)}};function En(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&En(t)}return Object.freeze(n)}i(En,"deepFreeze");var oe=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return En(this.#e)}get params(){return En(this.#t)}user};var Qt={},$e=[],mo=[],go=[],fo=[];var Tn={addPlugin(n){$e.push(n)},addRequestHook(n){mo.push(n)},addResponseSendingHook(n){go.push(n)},addResponseSendingFinalHook(n){fo.push(n)}},Hs=i(async(n,e)=>{if(mo.length===0)return n;let t=Qe.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of mo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof oe||c instanceof Response)return u.end(),c;{let l=new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Qe.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Fs=i(async(n,e,t)=>{if(go.length===0)return n;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of go)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Qe.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),$s=i(async(n,e,t)=>{if(fo.length===0)return;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of fo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Qe.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Zs=!1;async function js(n){if(!Zs){n&&(y("runtime.extensions"),await n(Tn)),Qt.value=Tn;for(let e of $e)if(e instanceof bt){let{requestHandlerProxy:t}=e.instrument({accountName:m.instance.build.ACCOUNT_NAME,projectName:m.instance.build.PROJECT_NAME,buildId:m.instance.build.BUILD_ID,zuploVersion:m.instance.build.ZUPLO_VERSION,compatibilityDate:m.instance.build.COMPATIBILITY_DATE,instanceId:m.instance.instanceId,environmentType:m.instance.loggingEnvironmentType,environmentStage:m.instance.loggingEnvironmentStage,deploymentName:m.instance.deploymentName});Ns(t)}for(let e of $e)e instanceof Fe&&await e.initialize(Tn);Jt.setProblemResponseFormat(Tn.problemResponseFormat),Zs=!0}}i(js,"initializeRuntime");var xn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function On(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(xn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(xn.Json)||!e?JSON.stringify(n):n}i(On,"serialize");function wt(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(wt,"isSystemRoute");var he=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>vn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:vn.SpanStatusCode.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let I=a.pop();return I?I(o,s,t,u):await this.#e(async $=>{let N=await r($,s);return Ql(N)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(wt(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Rt(o,l);s.dispatchEvent(p);let g=Pe.getContextExtensions(s),h=g.latestRequest,v;try{v=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{v=await g.onResponseSending(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{v=await Fs(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new Pt(o,v));try{await g.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await $s(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return v},"#toZuploPipeline")};function Ql(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(On(n),{headers:{"content-type":"application/json"}})}i(Ql,"resultToResponse");var Yt=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Yt||{}),zs={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 Yl={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"},Cn=Yl;function Xl(n){return`${new URL(n.url).pathname}`}i(Xl,"instance");function ed(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(ct);return r&&(t.rayId=r),t}i(ed,"trace");var td=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Xl(e),trace:ed(e,t),...r},additionalHeaders:o,statusText:Cn[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:zs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=td(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var Ye=class extends Ke{static{i(this,"MetricsPlugin")}};var te=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new Q(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ee=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new ee("ellie-metrics-transport",10,this.dispatchFunction,te.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=m.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=m.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Us(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":m.instance.deploymentName??"unknown","user-agent":m.instance.systemUserAgent}});if(!l.ok){let d=await l.text();te.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),qs(u)}},"dispatchFunction")};var pe=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Xt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Xt={name:"__system-no-version",pathPrefix:""};var Ie=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ct)??void 0,c=n.headers.get(Ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Sn(e)),$e.forEach(v=>{if(v instanceof Ye){let b=v.getTransport();h.push(b)}}),h.forEach(v=>{v.pushMetrics(g,e)}),a},"metricsProcessor");var Me=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(Me||{});var yo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=m.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new he({processors:[Ie],handler:t,gateway:e}),o=new pe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:nd}=Object.prototype,{propertyIsEnumerable:rd}=Object.prototype;function bo(n){return nd.call(n)}i(bo,"toString");function Oe(n){return typeof n=="string"}i(Oe,"isString");function It(n){return Oe(n)&&n!==""}i(It,"isNonEmptyString");function Bs(n){return bo(n)==="[object RegExp]"}i(Bs,"isRegexp");function Gs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>rd.call(n,e))]}i(Gs,"getOwnEnumerableKeys");function lt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(lt,"isObject");function wo(n){return typeof n=="number"&&!isNaN(n)}i(wo,"isNumber");function Ro(n){return n===!0||n===!1}i(Ro,"isBoolean");function Vs(n){return typeof n>"u"}i(Vs,"isUndefined");function Ws(n){return Vs(n)||n===null}i(Ws,"isUndefinedOrNull");function en(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(en,"isErrorLike");var Ks=new Map;function Xe(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Ks.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ks.set(n,r),r}i(Xe,"statusCodesStringToNumberArray");function dt(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(dt,"getValueFromRequestUser");function pt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("Received an array that contains non-string values.");return n}if(Oe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new f(`Expected type of string, received type '${typeof n}'`)}i(pt,"parseValueToStringArray");function Js(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!lt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!It(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Ro(t.allowCredentials))throw new f("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=Po(t,"allowedHeaders"),o=Po(t,"allowedMethods"),s=Po(t,"exposeHeaders"),a;try{a=pt(t.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Js,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=pt(n[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Po,"parseOptionalProperty");var An=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),_n=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var Io=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return x.notFound(a,u);let h=g.routeConfiguration,v=od(l,d,p,h,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),x.notFound(a,u))},"optionsHandler"),o=new he({processors:[Ie],handler:r,gateway:e}),s=new pe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),od=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=An(a.allowedOrigins,t);return u?{isValid:!0,headers:_n(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Qs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new he({processors:[Ie],handler:t,gateway:e}),o=new pe({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Eo=new pe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ys=i((n,e)=>{let t=i(async(o,s)=>{let a=Qt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var id=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xs=i(n=>{id.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Xs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=sd(o,t.routeData.corsPolicies),u=ad(n,a),c=new Headers(s.headers);return Xs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),sd=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ad=i((n,e)=>{let t=An(e.allowedOrigins,n.headers.get("origin"));return t?_n(e,t):{}},"getCorsHeaders");var To=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:m.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new he({processors:[Ln],handler:t,gateway:e}),o=new pe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var Et=require("@opentelemetry/api");var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var kn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Oe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},le=class extends kn{static{i(this,"InboundPolicy")}},je=class extends kn{static{i(this,"OutboundPolicy")}};var vo=class extends le{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Co=class extends je{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},xo=new Map;function tn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!xo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new f(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof le)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new vo(u,a.handler.options,a.name);else throw new f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new f(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);xo.set(a.name,c)}),t.map(s=>{let a=xo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(tn,"getInboundPolicyInstances");var Oo=new Map;function ud(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Oo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new f(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof je)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Co(a,s.handler.options??{},s.name);else throw new f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Oo.set(s.name,u)}),t.map(o=>{let s=Oo.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(ud,"getOutboundPolicyInstances");var So=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof oe||p instanceof Response)return d.end(),p;{let g=new f(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Et.SpanStatusCode.ERROR}),d.recordException(g),g}});if(l instanceof oe)u=l;else if(l instanceof Request)u=new oe(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),cd=i(n=>async(e,t,r)=>{let o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let g=new f(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Et.SpanStatusCode.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Nn=i(async(n,e,t,r)=>{let o=tn(e.route,t.routeData.policies),s=ud(e.route,t.routeData.policies);return ta({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ea({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ta({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ea,"createInternalPolicyProcessor");async function ta({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=So(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=cd(r),d;return m.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(ta,"executePolicyProcessor");function na(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ld,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=dd(l,o)}s=u+1}return t}i(na,"parse");function ld(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ld,"decode");function dd(n,e){try{return e(n)}catch{return n}}i(dd,"tryDecode");function ra(n,e){try{let t=/v\d+(-\d+)?/g,o=na(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ra,"devPortalBaseURL");var oa="/__zuplo/dev-portal",pd="dev-portal-id",md="dev-portal-host",gd="zp-account",fd="zp-project",hd="dev-portal-build",yd=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var U=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var i=(e,t)=>U(e,"name",{value:t,configurable:!0});var G=(e,t)=>{for(var n in t)U(e,n,{get:t[n],enumerable:!0})},k=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of x(t))!V.call(e,l)&&l!==n&&U(e,l,{get:()=>t[l],enumerable:!(o=w(t,l))||o.enumerable});return e};var B=e=>k(U({},"__esModule",{value:!0}),e);var H={};G(H,{getIdForParameterSchema:()=>D,getIdForRefSchema:()=>M,getIdForRequestBodySchema:()=>S,getRawOperationDataIdentifierName:()=>v,isRestrictedEnvVariableName:()=>R,isZuploReadableEnvVariableName:()=>T,sanitizedIdentifierName:()=>O});module.exports=B(H);function F(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let r=0;r<t.length;r++)t[r]=255;for(let r=0;r<e.length;r++){let s=e.charAt(r),d=s.charCodeAt(0);if(t[d]!==255)throw new TypeError(s+" is ambiguous");t[d]=r}let n=e.length,o=e.charAt(0),l=Math.log(n)/Math.log(256),E=Math.log(256)/Math.log(n);function L(r){if(r instanceof Uint8Array||(ArrayBuffer.isView(r)?r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Array.isArray(r)&&(r=Uint8Array.from(r))),!(r instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(r.length===0)return"";let s=0,d=0,_=0,c=r.length;for(;_!==c&&r[_]===0;)_++,s++;let f=(c-_)*E+1>>>0,g=new Uint8Array(f);for(;_!==c;){let a=r[_],h=0;for(let m=f-1;(a!==0||h<d)&&m!==-1;m--,h++)a+=256*g[m]>>>0,g[m]=a%n>>>0,a=a/n>>>0;if(a!==0)throw new Error("Non-zero carry");d=h,_++}let p=f-d;for(;p!==f&&g[p]===0;)p++;let P=o.repeat(s);for(;p<f;++p)P+=e.charAt(g[p]);return P}i(L,"encode");function I(r){if(typeof r!="string")throw new TypeError("Expected String");if(r.length===0)return new Uint8Array;let s=0,d=0,_=0;for(;r[s]===o;)d++,s++;let c=(r.length-s)*l+1>>>0,f=new Uint8Array(c);for(;r[s];){let a=t[r.charCodeAt(s)];if(a===255)return;let h=0;for(let m=c-1;(a!==0||h<_)&&m!==-1;m--,h++)a+=n*f[m]>>>0,f[m]=a%256>>>0,a=a/256>>>0;if(a!==0)throw new Error("Non-zero carry");_=h,s++}let g=c-_;for(;g!==c&&f[g]===0;)g++;let p=new Uint8Array(d+(c-g)),P=d;for(;g!==c;)p[P++]=f[g++];return p}i(I,"decodeUnsafe");function Z(r){let s=I(r);if(s)return s;throw new Error("Non-base"+n+" character")}return i(Z,"decode"),{encode:L,decodeUnsafe:I,decode:Z}}i(F,"base");var y=F;var z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",N=y(z);var A="2024-03-14",C=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function b(){return new u({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:A,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:C[A]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(b,"getMockEnvironment");var u=class e{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=b()),this.#e}constructor({build:t,runtime:n}){let o;try{if(n.__ZUPLO_CONFIG){let l=atob(n.__ZUPLO_CONFIG);o=JSON.parse(l)}if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let l=new TextDecoder().decode(N.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),E=JSON.parse(l);for(let L of Object.keys(E))n[L]=E[L]}}catch(l){console.error("Failed to parse runtime configuration",l)}this.config=o??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Y=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function R(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!Y.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(R,"isRestrictedEnvVariableName");function T(e){return!!e.startsWith("ZUPLO_")}i(T,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(e,t){let n=String(t);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return u.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return u.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return u.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return u.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return u.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return u.instance.build.BUILD_ID}if(!(R(n)&&!T(n)))return u.instance.runtime[n]}});function v(e,t,n){return`_${O(e+"_"+t+"_"+n)}`}i(v,"getRawOperationDataIdentifierName");function D(e,t,n,o){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+"_"+n.toLowerCase()+`_${o.toLowerCase()}`}i(D,"getIdForParameterSchema");function S(e,t,n){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${O(n.toLowerCase())}`}i(S,"getIdForRequestBodySchema");function M(e,t){return`_${O(e)}__${O(t)}`}i(M,"getIdForRefSchema");function O(e){let t=[];for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?t.push(e.charAt(n)):t.push("_")}return t.join("")}i(O,"sanitizedIdentifierName");
25
+ "use strict";var U=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var i=(e,t)=>U(e,"name",{value:t,configurable:!0});var G=(e,t)=>{for(var n in t)U(e,n,{get:t[n],enumerable:!0})},k=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of x(t))!V.call(e,l)&&l!==n&&U(e,l,{get:()=>t[l],enumerable:!(o=w(t,l))||o.enumerable});return e};var B=e=>k(U({},"__esModule",{value:!0}),e);var H={};G(H,{getIdForParameterSchema:()=>D,getIdForRefSchema:()=>M,getIdForRequestBodySchema:()=>S,getRawOperationDataIdentifierName:()=>v,isRestrictedEnvVariableName:()=>R,isZuploReadableEnvVariableName:()=>T,sanitizedIdentifierName:()=>O});module.exports=B(H);function F(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let r=0;r<t.length;r++)t[r]=255;for(let r=0;r<e.length;r++){let s=e.charAt(r),d=s.charCodeAt(0);if(t[d]!==255)throw new TypeError(s+" is ambiguous");t[d]=r}let n=e.length,o=e.charAt(0),l=Math.log(n)/Math.log(256),E=Math.log(256)/Math.log(n);function L(r){if(r instanceof Uint8Array||(ArrayBuffer.isView(r)?r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Array.isArray(r)&&(r=Uint8Array.from(r))),!(r instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(r.length===0)return"";let s=0,d=0,_=0,c=r.length;for(;_!==c&&r[_]===0;)_++,s++;let f=(c-_)*E+1>>>0,g=new Uint8Array(f);for(;_!==c;){let a=r[_],h=0;for(let m=f-1;(a!==0||h<d)&&m!==-1;m--,h++)a+=256*g[m]>>>0,g[m]=a%n>>>0,a=a/n>>>0;if(a!==0)throw new Error("Non-zero carry");d=h,_++}let p=f-d;for(;p!==f&&g[p]===0;)p++;let P=o.repeat(s);for(;p<f;++p)P+=e.charAt(g[p]);return P}i(L,"encode");function I(r){if(typeof r!="string")throw new TypeError("Expected String");if(r.length===0)return new Uint8Array;let s=0,d=0,_=0;for(;r[s]===o;)d++,s++;let c=(r.length-s)*l+1>>>0,f=new Uint8Array(c);for(;r[s];){let a=t[r.charCodeAt(s)];if(a===255)return;let h=0;for(let m=c-1;(a!==0||h<_)&&m!==-1;m--,h++)a+=n*f[m]>>>0,f[m]=a%256>>>0,a=a/256>>>0;if(a!==0)throw new Error("Non-zero carry");_=h,s++}let g=c-_;for(;g!==c&&f[g]===0;)g++;let p=new Uint8Array(d+(c-g)),P=d;for(;g!==c;)p[P++]=f[g++];return p}i(I,"decodeUnsafe");function Z(r){let s=I(r);if(s)return s;throw new Error("Non-base"+n+" character")}return i(Z,"decode"),{encode:L,decodeUnsafe:I,decode:Z}}i(F,"base");var y=F;var z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",N=y(z);var A="2024-03-14",C=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function b(){return new u({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:A,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:C[A]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(b,"getMockEnvironment");var u=class e{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=b()),this.#e}constructor({build:t,runtime:n}){let o;try{if(n.__ZUPLO_CONFIG){let l=atob(n.__ZUPLO_CONFIG);o=JSON.parse(l)}if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let l=new TextDecoder().decode(N.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),E=JSON.parse(l);for(let L of Object.keys(E))n[L]=E[L]}}catch(l){console.error("Failed to parse runtime configuration",l)}this.config=o??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Y=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function R(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!Y.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(R,"isRestrictedEnvVariableName");function T(e){return!!e.startsWith("ZUPLO_")}i(T,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(e,t){let n=String(t);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return u.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return u.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return u.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return u.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return u.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return u.instance.build.BUILD_ID}if(!(R(n)&&!T(n)))return u.instance.runtime[n]}});function v(e,t,n){return`_${O(e+"_"+t+"_"+n)}`}i(v,"getRawOperationDataIdentifierName");function D(e,t,n,o){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+"_"+n.toLowerCase()+`_${o.toLowerCase()}`}i(D,"getIdForParameterSchema");function S(e,t,n){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${O(n.toLowerCase())}`}i(S,"getIdForRequestBodySchema");function M(e,t){return`_${O(e)}__${O(t)}`}i(M,"getIdForRefSchema");function O(e){let t=[];for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?t.push(e.charAt(n)):t.push("_")}return t.join("")}i(O,"sanitizedIdentifierName");
26
26
  /*! For license information please see index.js.LEGAL.txt */
@@ -32,5 +32,5 @@
32
32
  `))):g=e.stylize("[Circular]","special")),ae(o)){if(f&&s.match(/^\d+$/))return g;o=JSON.stringify(""+s),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+g}n(Y,"formatProperty");function It(e,t){if(ae(t))return e.stylize("undefined","undefined");if(ge(t)){let r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(Ct(t))return e.stylize(""+t,"number");if(Ut(t))return e.stylize(""+t,"boolean");if(fe(t))return e.stylize("null","null")}n(It,"formatPrimitive");function vt(e,t,r){let u=0;return e.reduce(function(f,o){return u++,o.indexOf(`
33
33
  `)>=0&&u++,f+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(t===""?"":t+`
34
34
  `)+" "+e.join(`,
35
- `)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}n(vt,"reduceToSingleString")});var pe=N(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.format=void 0;var Mt=ce(),zt=de(),Bt=n((e,...t)=>(0,Mt.format)(zt.inspect,e,t),"format");x.format=Bt});var be=N(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.debug=L.withoutEnv=L.Debugger=void 0;var xt=ue(),kt=pe(),k=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,r){this.manager=t,this.ns=r,this.color=(0,xt.generateColor)(r),this.last=0,this.enabled=t.enabled.some(u=>u.test(r))}log(...t){if(!this.enabled)return;let r,u=t[0];typeof u=="function"?r=u():r=String(u);let s=Date.now()-(this.last||Date.now());r=(0,kt.format)(r,...t);let f=`${this.color(this.ns)} ${r} ${this.color(`+${s}ms`)}`;console.log(f),this.last=Date.now()}};L.Debugger=k;var Z=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function me(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(me,"extract");var I;function Zt(e){e||(e=[]),typeof e=="string"&&(e=me(e)),I=new Z(e)}n(Zt,"withoutEnv");L.withoutEnv=Zt;function Dt(e){let t=globalThis.DEBUG;I||(I=new Z(me(t)));let r=new k(I,e);return I.debuggers.set(e,r),Object.assign(r.log.bind(r),{self:r})}n(Dt,"debug");L.debug=Dt});var qt={};Ie(qt,{PdpService:()=>K});module.exports=Me(qt);var we=ve(be());var S=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,r){typeof t=="string"?super(t,r):(super(t.message,r),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};function jt(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let h=e.charAt(c),m=h.charCodeAt(0);if(t[m]!==255)throw new TypeError(h+" is ambiguous");t[m]=c}let r=e.length,u=e.charAt(0),s=Math.log(r)/Math.log(256),f=Math.log(256)/Math.log(r);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,m=0,b=0,y=c.length;for(;b!==y&&c[b]===0;)b++,h++;let E=(y-b)*f+1>>>0,_=new Uint8Array(E);for(;b!==y;){let p=c[b],A=0;for(let R=E-1;(p!==0||A<m)&&R!==-1;R--,A++)p+=256*_[R]>>>0,_[R]=p%r>>>0,p=p/r>>>0;if(p!==0)throw new Error("Non-zero carry");m=A,b++}let O=E-m;for(;O!==E&&_[O]===0;)O++;let v=u.repeat(h);for(;O<E;++O)v+=e.charAt(_[O]);return v}n(o,"encode");function g(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,m=0,b=0;for(;c[h]===u;)m++,h++;let y=(c.length-h)*s+1>>>0,E=new Uint8Array(y);for(;c[h];){let p=t[c.charCodeAt(h)];if(p===255)return;let A=0;for(let R=y-1;(p!==0||A<b)&&R!==-1;R--,A++)p+=r*E[R]>>>0,E[R]=p%256>>>0,p=p/256>>>0;if(p!==0)throw new Error("Non-zero carry");b=A,h++}let _=y-b;for(;_!==y&&E[_]===0;)_++;let O=new Uint8Array(m+(y-_)),v=m;for(;_!==y;)O[v++]=E[_++];return O}n(g,"decodeUnsafe");function d(c){let h=g(c);if(h)return h;throw new Error("Non-base"+r+" character")}return n(d,"decode"),{encode:o,decodeUnsafe:g,decode:d}}n(jt,"base");var _e=jt;var Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ye=_e(Ft);var W="2024-03-14",Ee=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Oe(){return new T({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:W,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:Ee[W]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(Oe,"getMockEnvironment");var T=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Oe()),this.#e}constructor({build:t,runtime:r}){let u;try{if(r.__ZUPLO_CONFIG){let s=atob(r.__ZUPLO_CONFIG);u=JSON.parse(s)}if(r.ZUPLO_SYSTEM_CONFIGURATIONS){let s=new TextDecoder().decode(ye.decode(r.ZUPLO_SYSTEM_CONFIGURATIONS)),f=JSON.parse(s);for(let o of Object.keys(f))r[o]=f[o]}}catch(s){console.error("Failed to parse runtime configuration",s)}this.config=u??{},this.build=t,this.runtime=r,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var C=(0,we.debug)("zuplo:runtime:external-service");function $t(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=T.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}n($t,"getServiceAuth");async function Le(e,t){let r=$t();if(r)if(C(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,f=t??{},o=new Headers(f.headers||{});o.set("CF-Access-Client-Id",r.clientId),o.set("CF-Access-Client-Secret",r.clientSecret),f.headers=o;let g;if(r.customServiceMapping&&r.customServiceMapping[s])g=`https://${r.customServiceMapping[s]}`;else if(T.instance.useLegacyServiceRouting)g=`https://${s}.zuptunnel.com`;else{C("Using sha256 service routing");let h=T.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)g=`https://${await Ht(s,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw C("Cannot use sha256 service routing, missing build variables"),new S("Failed to generate fully qualified tunnel url.")}let d=new URL(`${g}${u.pathname}${u.search}`);C(`Calling external service: ${d.toString()}`);let c=await D.fetch(d.toString(),f);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:g}),new S("Could not connect to secure tunnel.");return c}else throw C("Cannot call external service with Request object"),new S("Currently, we only support fetch(<some_string>, ...).");else throw C("There is no external service auth configured for this zup."),new S("There are no external services configured for this zup.")}n(Le,"externalServiceHandler");async function Ht(e,t,r,u){let s=e.toLowerCase(),f=t.toLowerCase(),o=r.toLowerCase(),g=Gt(u);C(`Hashing service name: ${f}-${s}.${f}-${o}-${g}`);let d=await Re(`${f}-${s}`),c=await Re(`${f}-${o}-${g}`);return`${d}.${c}`}n(Ht,"hashServiceName");async function Re(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(f=>f.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(Re,"hashSegment");function Gt(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(Gt,"sanitizeEnvironmentType");var Ae=new Map;Ae.set("service:",Le);var Te=globalThis.fetch;function J(e,t){let r=Yt(t);if(typeof e=="string"){let u=new URL(e),s=Ae.get(u.protocol);return s?s(e,r):Te(e,r)}else return Te(e,r)}n(J,"internalFetch");globalThis.fetch=J;var Yt=n(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Vt={fetch:J},D=Vt;var K=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{n(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let r=await D.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!r.ok)throw new Error(`Request to PDP service failed with response status ${r.status}.`);return await r.json()}};
35
+ `)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}n(vt,"reduceToSingleString")});var pe=N(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.format=void 0;var Mt=ce(),zt=de(),Bt=n((e,...t)=>(0,Mt.format)(zt.inspect,e,t),"format");x.format=Bt});var be=N(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.debug=L.withoutEnv=L.Debugger=void 0;var xt=ue(),kt=pe(),k=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,r){this.manager=t,this.ns=r,this.color=(0,xt.generateColor)(r),this.last=0,this.enabled=t.enabled.some(u=>u.test(r))}log(...t){if(!this.enabled)return;let r,u=t[0];typeof u=="function"?r=u():r=String(u);let s=Date.now()-(this.last||Date.now());r=(0,kt.format)(r,...t);let f=`${this.color(this.ns)} ${r} ${this.color(`+${s}ms`)}`;console.log(f),this.last=Date.now()}};L.Debugger=k;var Z=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function me(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(me,"extract");var I;function Zt(e){e||(e=[]),typeof e=="string"&&(e=me(e)),I=new Z(e)}n(Zt,"withoutEnv");L.withoutEnv=Zt;function Dt(e){let t=globalThis.DEBUG;I||(I=new Z(me(t)));let r=new k(I,e);return I.debuggers.set(e,r),Object.assign(r.log.bind(r),{self:r})}n(Dt,"debug");L.debug=Dt});var qt={};Ie(qt,{PdpService:()=>K});module.exports=Me(qt);var we=ve(be());var S=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,r){typeof t=="string"?super(t,r):(super(t.message,r),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};function jt(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let h=e.charAt(c),m=h.charCodeAt(0);if(t[m]!==255)throw new TypeError(h+" is ambiguous");t[m]=c}let r=e.length,u=e.charAt(0),s=Math.log(r)/Math.log(256),f=Math.log(256)/Math.log(r);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,m=0,b=0,y=c.length;for(;b!==y&&c[b]===0;)b++,h++;let E=(y-b)*f+1>>>0,_=new Uint8Array(E);for(;b!==y;){let p=c[b],A=0;for(let R=E-1;(p!==0||A<m)&&R!==-1;R--,A++)p+=256*_[R]>>>0,_[R]=p%r>>>0,p=p/r>>>0;if(p!==0)throw new Error("Non-zero carry");m=A,b++}let O=E-m;for(;O!==E&&_[O]===0;)O++;let v=u.repeat(h);for(;O<E;++O)v+=e.charAt(_[O]);return v}n(o,"encode");function g(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,m=0,b=0;for(;c[h]===u;)m++,h++;let y=(c.length-h)*s+1>>>0,E=new Uint8Array(y);for(;c[h];){let p=t[c.charCodeAt(h)];if(p===255)return;let A=0;for(let R=y-1;(p!==0||A<b)&&R!==-1;R--,A++)p+=r*E[R]>>>0,E[R]=p%256>>>0,p=p/256>>>0;if(p!==0)throw new Error("Non-zero carry");b=A,h++}let _=y-b;for(;_!==y&&E[_]===0;)_++;let O=new Uint8Array(m+(y-_)),v=m;for(;_!==y;)O[v++]=E[_++];return O}n(g,"decodeUnsafe");function d(c){let h=g(c);if(h)return h;throw new Error("Non-base"+r+" character")}return n(d,"decode"),{encode:o,decodeUnsafe:g,decode:d}}n(jt,"base");var _e=jt;var Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ye=_e(Ft);var W="2024-03-14",Ee=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Oe(){return new T({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:W,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:Ee[W]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(Oe,"getMockEnvironment");var T=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Oe()),this.#e}constructor({build:t,runtime:r}){let u;try{if(r.__ZUPLO_CONFIG){let s=atob(r.__ZUPLO_CONFIG);u=JSON.parse(s)}if(r.ZUPLO_SYSTEM_CONFIGURATIONS){let s=new TextDecoder().decode(ye.decode(r.ZUPLO_SYSTEM_CONFIGURATIONS)),f=JSON.parse(s);for(let o of Object.keys(f))r[o]=f[o]}}catch(s){console.error("Failed to parse runtime configuration",s)}this.config=u??{},this.build=t,this.runtime=r,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var C=(0,we.debug)("zuplo:runtime:external-service");function $t(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=T.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}n($t,"getServiceAuth");async function Le(e,t){let r=$t();if(r)if(C(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,f=t??{},o=new Headers(f.headers||{});o.set("CF-Access-Client-Id",r.clientId),o.set("CF-Access-Client-Secret",r.clientSecret),f.headers=o;let g;if(r.customServiceMapping&&r.customServiceMapping[s])g=`https://${r.customServiceMapping[s]}`;else if(T.instance.useLegacyServiceRouting)g=`https://${s}.zuptunnel.com`;else{C("Using sha256 service routing");let h=T.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)g=`https://${await Ht(s,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw C("Cannot use sha256 service routing, missing build variables"),new S("Failed to generate fully qualified tunnel url.")}let d=new URL(`${g}${u.pathname}${u.search}`);C(`Calling external service: ${d.toString()}`);let c=await D.fetch(d.toString(),f);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:g}),new S("Could not connect to secure tunnel.");return c}else throw C("Cannot call external service with Request object"),new S("Currently, we only support fetch(<some_string>, ...).");else throw C("There is no external service auth configured for this zup."),new S("There are no external services configured for this zup.")}n(Le,"externalServiceHandler");async function Ht(e,t,r,u){let s=e.toLowerCase(),f=t.toLowerCase(),o=r.toLowerCase(),g=Gt(u);C(`Hashing service name: ${f}-${s}.${f}-${o}-${g}`);let d=await Re(`${f}-${s}`),c=await Re(`${f}-${o}-${g}`);return`${d}.${c}`}n(Ht,"hashServiceName");async function Re(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(f=>f.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(Re,"hashSegment");function Gt(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(Gt,"sanitizeEnvironmentType");var Ae=new Map;Ae.set("service:",Le);var Te=globalThis.fetch;function J(e,t){let r=Yt(t);if(typeof e=="string"){let u=new URL(e),s=Ae.get(u.protocol);return s?s(e,r):Te(e,r)}else return Te(e,r)}n(J,"internalFetch");globalThis.fetch=J;var Yt=n(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Vt={fetch:J},D=Vt;var K=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{n(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let r=await D.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!r.ok)throw new Error(`Request to PDP service failed with response status ${r.status}.`);return await r.json()}};
36
36
  /*! For license information please see exports.js.LEGAL.txt */
@@ -0,0 +1,26 @@
1
+
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Zuplo, Inc. All rights reserved.
4
+ *
5
+ * This software and associated documentation files (the "Software") is intended to be used
6
+ * only by Zuplo customers solely to develop and test applications that will be deployed
7
+ * to Zuplo hosted services. You and others in your organization may use these files on your
8
+ * Development Devices solely for the above stated purpose.
9
+ *
10
+ * Outside of uses stated above, no license is granted for any other purpose including
11
+ * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
+ * sublicense, host, and/or sell copies of the Software.
13
+ *
14
+ * The software may include third party components with separate legal notices or governed by
15
+ * other agreements, as described in licenses either embedded in or accompanying the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
+ * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
+ * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ * DEALINGS IN THE SOFTWARE.
23
+ *--------------------------------------------------------------------------------------------*/
24
+
25
+ import{a as d}from"./chunk-PPV7V43C.js";function N(c){if(c.length>=255)throw new TypeError("Alphabet too long");let _=new Uint8Array(256);for(let e=0;e<_.length;e++)_[e]=255;for(let e=0;e<c.length;e++){let t=c.charAt(e),s=t.charCodeAt(0);if(_[s]!==255)throw new TypeError(t+" is ambiguous");_[s]=e}let i=c.length,h=c.charAt(0),f=Math.log(i)/Math.log(256),E=Math.log(256)/Math.log(i);function p(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let t=0,s=0,r=0,l=e.length;for(;r!==l&&e[r]===0;)r++,t++;let u=(l-r)*E+1>>>0,o=new Uint8Array(u);for(;r!==l;){let n=e[r],m=0;for(let g=u-1;(n!==0||m<s)&&g!==-1;g--,m++)n+=256*o[g]>>>0,o[g]=n%i>>>0,n=n/i>>>0;if(n!==0)throw new Error("Non-zero carry");s=m,r++}let a=u-s;for(;a!==u&&o[a]===0;)a++;let L=h.repeat(t);for(;a<u;++a)L+=c.charAt(o[a]);return L}d(p,"encode");function T(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let t=0,s=0,r=0;for(;e[t]===h;)s++,t++;let l=(e.length-t)*f+1>>>0,u=new Uint8Array(l);for(;e[t];){let n=_[e.charCodeAt(t)];if(n===255)return;let m=0;for(let g=l-1;(n!==0||m<r)&&g!==-1;g--,m++)n+=i*u[g]>>>0,u[g]=n%256>>>0,n=n/256>>>0;if(n!==0)throw new Error("Non-zero carry");r=m,t++}let o=l-r;for(;o!==l&&u[o]===0;)o++;let a=new Uint8Array(s+(l-o)),L=s;for(;o!==l;)a[L++]=u[o++];return a}d(T,"decodeUnsafe");function R(e){let t=T(e);if(t)return t;throw new Error("Non-base"+i+" character")}return d(R,"decode"),{encode:p,decodeUnsafe:T,decode:R}}d(N,"base");var A=N;var b="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",P=A(b);var U="2024-03-14",y=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function I(){return new O({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:U,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:y[U]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}d(I,"getMockEnvironment");var O=class c{static{d(this,"Environment")}config;static#e;static#t=!1;static initialize(_){this.#e||(this.#e=new c(_),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=I()),this.#e}constructor({build:_,runtime:i}){let h;try{if(i.__ZUPLO_CONFIG){let f=atob(i.__ZUPLO_CONFIG);h=JSON.parse(f)}if(i.ZUPLO_SYSTEM_CONFIGURATIONS){let f=new TextDecoder().decode(P.decode(i.ZUPLO_SYSTEM_CONFIGURATIONS)),E=JSON.parse(f);for(let p of Object.keys(E))i[p]=E[p]}}catch(f){console.error("Failed to parse runtime configuration",f)}this.config=h??{},this.build=_,this.runtime=i,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.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 authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}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.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{O as a};
26
+ /*! For license information please see chunk-NFVGBDMC.js.LEGAL.txt */
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as E}from"./chunk-HAXIE4MQ.js";import{a as r,b as R,c as he}from"./chunk-PPV7V43C.js";var V=R(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});n.generateColor=n.colorFunctions=n.stripColor=n.bgRgb24=n.rgb24=n.bgRgb8=n.rgb8=n.bgBrightWhite=n.bgBrightCyan=n.bgBrightMagenta=n.bgBrightBlue=n.bgBrightYellow=n.bgBrightGreen=n.bgBrightRed=n.bgBrightBlack=n.bgWhite=n.bgCyan=n.bgMagenta=n.bgBlue=n.bgYellow=n.bgGreen=n.bgRed=n.bgBlack=n.brightWhite=n.brightCyan=n.brightMagenta=n.brightBlue=n.brightYellow=n.brightGreen=n.brightRed=n.brightBlack=n.gray=n.white=n.cyan=n.magenta=n.blue=n.yellow=n.green=n.red=n.black=n.strikethrough=n.hidden=n.inverse=n.underline=n.italic=n.dim=n.bold=n.reset=n.getColorEnabled=n.setColorEnabled=void 0;var F=!0,$=!F;function pe(e){F||($=e)}r(pe,"setColorEnabled");n.setColorEnabled=pe;function de(){return $}r(de,"getColorEnabled");n.getColorEnabled=de;function s(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(s,"code");function c(e,t){return $?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(c,"run");function be(e){return c(e,s([0],0))}r(be,"reset");n.reset=be;function me(e){return c(e,s([1],22))}r(me,"bold");n.bold=me;function ye(e){return c(e,s([2],22))}r(ye,"dim");n.dim=ye;function we(e){return c(e,s([3],23))}r(we,"italic");n.italic=we;function Re(e){return c(e,s([4],24))}r(Re,"underline");n.underline=Re;function Ce(e){return c(e,s([7],27))}r(Ce,"inverse");n.inverse=Ce;function Ee(e){return c(e,s([8],28))}r(Ee,"hidden");n.hidden=Ee;function Se(e){return c(e,s([9],29))}r(Se,"strikethrough");n.strikethrough=Se;function Oe(e){return c(e,s([30],39))}r(Oe,"black");n.black=Oe;function L(e){return c(e,s([31],39))}r(L,"red");n.red=L;function Y(e){return c(e,s([32],39))}r(Y,"green");n.green=Y;function D(e){return c(e,s([33],39))}r(D,"yellow");n.yellow=D;function G(e){return c(e,s([34],39))}r(G,"blue");n.blue=G;function J(e){return c(e,s([35],39))}r(J,"magenta");n.magenta=J;function W(e){return c(e,s([36],39))}r(W,"cyan");n.cyan=W;function Be(e){return c(e,s([37],39))}r(Be,"white");n.white=Be;function ze(e){return Z(e)}r(ze,"gray");n.gray=ze;function Z(e){return c(e,s([90],39))}r(Z,"brightBlack");n.brightBlack=Z;function Ae(e){return c(e,s([91],39))}r(Ae,"brightRed");n.brightRed=Ae;function Ne(e){return c(e,s([92],39))}r(Ne,"brightGreen");n.brightGreen=Ne;function Me(e){return c(e,s([93],39))}r(Me,"brightYellow");n.brightYellow=Me;function $e(e){return c(e,s([94],39))}r($e,"brightBlue");n.brightBlue=$e;function ve(e){return c(e,s([95],39))}r(ve,"brightMagenta");n.brightMagenta=ve;function xe(e){return c(e,s([96],39))}r(xe,"brightCyan");n.brightCyan=xe;function Te(e){return c(e,s([97],39))}r(Te,"brightWhite");n.brightWhite=Te;function _e(e){return c(e,s([40],49))}r(_e,"bgBlack");n.bgBlack=_e;function je(e){return c(e,s([41],49))}r(je,"bgRed");n.bgRed=je;function Ie(e){return c(e,s([42],49))}r(Ie,"bgGreen");n.bgGreen=Ie;function Pe(e){return c(e,s([43],49))}r(Pe,"bgYellow");n.bgYellow=Pe;function Ue(e){return c(e,s([44],49))}r(Ue,"bgBlue");n.bgBlue=Ue;function He(e){return c(e,s([45],49))}r(He,"bgMagenta");n.bgMagenta=He;function qe(e){return c(e,s([46],49))}r(qe,"bgCyan");n.bgCyan=qe;function ke(e){return c(e,s([47],49))}r(ke,"bgWhite");n.bgWhite=ke;function Fe(e){return c(e,s([100],49))}r(Fe,"bgBrightBlack");n.bgBrightBlack=Fe;function Le(e){return c(e,s([101],49))}r(Le,"bgBrightRed");n.bgBrightRed=Le;function Ye(e){return c(e,s([102],49))}r(Ye,"bgBrightGreen");n.bgBrightGreen=Ye;function De(e){return c(e,s([103],49))}r(De,"bgBrightYellow");n.bgBrightYellow=De;function Ge(e){return c(e,s([104],49))}r(Ge,"bgBrightBlue");n.bgBrightBlue=Ge;function Je(e){return c(e,s([105],49))}r(Je,"bgBrightMagenta");n.bgBrightMagenta=Je;function We(e){return c(e,s([106],49))}r(We,"bgBrightCyan");n.bgBrightCyan=We;function Ze(e){return c(e,s([107],49))}r(Ze,"bgBrightWhite");n.bgBrightWhite=Ze;function b(e,t=255,i=0){return Math.trunc(Math.max(Math.min(e,t),i))}r(b,"clampAndTruncate");function Ve(e,t){return c(e,s([38,5,b(t)],39))}r(Ve,"rgb8");n.rgb8=Ve;function Xe(e,t){return c(e,s([48,5,b(t)],49))}r(Xe,"bgRgb8");n.bgRgb8=Xe;function Ke(e,t){return typeof t=="number"?c(e,s([38,2,t>>16&255,t>>8&255,t&255],39)):c(e,s([38,2,b(t.r),b(t.g),b(t.b)],39))}r(Ke,"rgb24");n.rgb24=Ke;function Qe(e,t){return typeof t=="number"?c(e,s([48,2,t>>16&255,t>>8&255,t&255],49)):c(e,s([48,2,b(t.r),b(t.g),b(t.b)],49))}r(Qe,"bgRgb24");n.bgRgb24=Qe;var et=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function tt(e){return e.replace(et,"")}r(tt,"stripColor");n.stripColor=tt;n.colorFunctions=[L,Y,D,G,J,W];function nt(e){let t=0,i=e.length,u=0;if(i>0)for(;u<i;)t=(t<<5)-t+e.charCodeAt(u++)|0;return t}r(nt,"hashCode");function rt(e){let t=Math.abs(nt(e));return n.colorFunctions[t%n.colorFunctions.length]}r(rt,"generateColor");n.generateColor=rt});var X=R(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.format=void 0;function it(e,t,...i){let u=0,a=i.length,g=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(u>=a)return o;switch(o){case"%s":return String(i[u++]);case"%d":return Number(i[u++]).toString();case"%o":return e(i[u++]).split(`
25
+ import{a as E}from"./chunk-NFVGBDMC.js";import{a as r,b as R,c as he}from"./chunk-PPV7V43C.js";var V=R(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});n.generateColor=n.colorFunctions=n.stripColor=n.bgRgb24=n.rgb24=n.bgRgb8=n.rgb8=n.bgBrightWhite=n.bgBrightCyan=n.bgBrightMagenta=n.bgBrightBlue=n.bgBrightYellow=n.bgBrightGreen=n.bgBrightRed=n.bgBrightBlack=n.bgWhite=n.bgCyan=n.bgMagenta=n.bgBlue=n.bgYellow=n.bgGreen=n.bgRed=n.bgBlack=n.brightWhite=n.brightCyan=n.brightMagenta=n.brightBlue=n.brightYellow=n.brightGreen=n.brightRed=n.brightBlack=n.gray=n.white=n.cyan=n.magenta=n.blue=n.yellow=n.green=n.red=n.black=n.strikethrough=n.hidden=n.inverse=n.underline=n.italic=n.dim=n.bold=n.reset=n.getColorEnabled=n.setColorEnabled=void 0;var F=!0,$=!F;function pe(e){F||($=e)}r(pe,"setColorEnabled");n.setColorEnabled=pe;function de(){return $}r(de,"getColorEnabled");n.getColorEnabled=de;function s(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(s,"code");function c(e,t){return $?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(c,"run");function be(e){return c(e,s([0],0))}r(be,"reset");n.reset=be;function me(e){return c(e,s([1],22))}r(me,"bold");n.bold=me;function ye(e){return c(e,s([2],22))}r(ye,"dim");n.dim=ye;function we(e){return c(e,s([3],23))}r(we,"italic");n.italic=we;function Re(e){return c(e,s([4],24))}r(Re,"underline");n.underline=Re;function Ce(e){return c(e,s([7],27))}r(Ce,"inverse");n.inverse=Ce;function Ee(e){return c(e,s([8],28))}r(Ee,"hidden");n.hidden=Ee;function Se(e){return c(e,s([9],29))}r(Se,"strikethrough");n.strikethrough=Se;function Oe(e){return c(e,s([30],39))}r(Oe,"black");n.black=Oe;function L(e){return c(e,s([31],39))}r(L,"red");n.red=L;function Y(e){return c(e,s([32],39))}r(Y,"green");n.green=Y;function D(e){return c(e,s([33],39))}r(D,"yellow");n.yellow=D;function G(e){return c(e,s([34],39))}r(G,"blue");n.blue=G;function J(e){return c(e,s([35],39))}r(J,"magenta");n.magenta=J;function W(e){return c(e,s([36],39))}r(W,"cyan");n.cyan=W;function Be(e){return c(e,s([37],39))}r(Be,"white");n.white=Be;function ze(e){return Z(e)}r(ze,"gray");n.gray=ze;function Z(e){return c(e,s([90],39))}r(Z,"brightBlack");n.brightBlack=Z;function Ae(e){return c(e,s([91],39))}r(Ae,"brightRed");n.brightRed=Ae;function Ne(e){return c(e,s([92],39))}r(Ne,"brightGreen");n.brightGreen=Ne;function Me(e){return c(e,s([93],39))}r(Me,"brightYellow");n.brightYellow=Me;function $e(e){return c(e,s([94],39))}r($e,"brightBlue");n.brightBlue=$e;function ve(e){return c(e,s([95],39))}r(ve,"brightMagenta");n.brightMagenta=ve;function xe(e){return c(e,s([96],39))}r(xe,"brightCyan");n.brightCyan=xe;function Te(e){return c(e,s([97],39))}r(Te,"brightWhite");n.brightWhite=Te;function _e(e){return c(e,s([40],49))}r(_e,"bgBlack");n.bgBlack=_e;function je(e){return c(e,s([41],49))}r(je,"bgRed");n.bgRed=je;function Ie(e){return c(e,s([42],49))}r(Ie,"bgGreen");n.bgGreen=Ie;function Pe(e){return c(e,s([43],49))}r(Pe,"bgYellow");n.bgYellow=Pe;function Ue(e){return c(e,s([44],49))}r(Ue,"bgBlue");n.bgBlue=Ue;function He(e){return c(e,s([45],49))}r(He,"bgMagenta");n.bgMagenta=He;function qe(e){return c(e,s([46],49))}r(qe,"bgCyan");n.bgCyan=qe;function ke(e){return c(e,s([47],49))}r(ke,"bgWhite");n.bgWhite=ke;function Fe(e){return c(e,s([100],49))}r(Fe,"bgBrightBlack");n.bgBrightBlack=Fe;function Le(e){return c(e,s([101],49))}r(Le,"bgBrightRed");n.bgBrightRed=Le;function Ye(e){return c(e,s([102],49))}r(Ye,"bgBrightGreen");n.bgBrightGreen=Ye;function De(e){return c(e,s([103],49))}r(De,"bgBrightYellow");n.bgBrightYellow=De;function Ge(e){return c(e,s([104],49))}r(Ge,"bgBrightBlue");n.bgBrightBlue=Ge;function Je(e){return c(e,s([105],49))}r(Je,"bgBrightMagenta");n.bgBrightMagenta=Je;function We(e){return c(e,s([106],49))}r(We,"bgBrightCyan");n.bgBrightCyan=We;function Ze(e){return c(e,s([107],49))}r(Ze,"bgBrightWhite");n.bgBrightWhite=Ze;function b(e,t=255,i=0){return Math.trunc(Math.max(Math.min(e,t),i))}r(b,"clampAndTruncate");function Ve(e,t){return c(e,s([38,5,b(t)],39))}r(Ve,"rgb8");n.rgb8=Ve;function Xe(e,t){return c(e,s([48,5,b(t)],49))}r(Xe,"bgRgb8");n.bgRgb8=Xe;function Ke(e,t){return typeof t=="number"?c(e,s([38,2,t>>16&255,t>>8&255,t&255],39)):c(e,s([38,2,b(t.r),b(t.g),b(t.b)],39))}r(Ke,"rgb24");n.rgb24=Ke;function Qe(e,t){return typeof t=="number"?c(e,s([48,2,t>>16&255,t>>8&255,t&255],49)):c(e,s([48,2,b(t.r),b(t.g),b(t.b)],49))}r(Qe,"bgRgb24");n.bgRgb24=Qe;var et=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function tt(e){return e.replace(et,"")}r(tt,"stripColor");n.stripColor=tt;n.colorFunctions=[L,Y,D,G,J,W];function nt(e){let t=0,i=e.length,u=0;if(i>0)for(;u<i;)t=(t<<5)-t+e.charCodeAt(u++)|0;return t}r(nt,"hashCode");function rt(e){let t=Math.abs(nt(e));return n.colorFunctions[t%n.colorFunctions.length]}r(rt,"generateColor");n.generateColor=rt});var X=R(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.format=void 0;function it(e,t,...i){let u=0,a=i.length,g=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(u>=a)return o;switch(o){case"%s":return String(i[u++]);case"%d":return Number(i[u++]).toString();case"%o":return e(i[u++]).split(`
26
26
  `).map(l=>l.trim()).join(" ");case"%O":return e(i[u++]);case"%j":try{return JSON.stringify(i[u++])}catch{return"[Circular]"}default:return o}});for(let o of i.splice(u))o===null||!(typeof o=="object"&&o!==null)?g+=" "+o:g+=" "+e(o);return g}r(it,"format");S.format=it});var re=R(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.inspect=void 0;function y(e,t,i,u){let a={seen:[],stylize:ot,showHidden:t??!1,depth:i??2,colors:u??!1,customInspect:!0};return a.colors&&(a.stylize=ct),O(a,e,a.depth)}r(y,"inspect");B.inspect=y;y.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};y.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ot(e,t){return e}r(ot,"stylizeNoColor");function st(e){return typeof e=="boolean"}r(st,"isBoolean");function Q(e){return e===void 0}r(Q,"isUndefined");function ct(e,t){let i=y.styles[t];return i?"\x1B["+y.colors[i][0]+"m"+e+"\x1B["+y.colors[i][1]+"m":e}r(ct,"stylizeWithColor");function v(e){return typeof e=="function"}r(v,"isFunction");function ee(e){return typeof e=="string"}r(ee,"isString");function ut(e){return typeof e=="number"}r(ut,"isNumber");function te(e){return e===null}r(te,"isNull");function ne(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(ne,"hasOwn");function x(e){return I(e)&&P(e)==="[object RegExp]"}r(x,"isRegExp");function I(e){return typeof e=="object"&&e!==null}r(I,"isObject");function T(e){return I(e)&&(P(e)==="[object Error]"||e instanceof Error)}r(T,"isError");function K(e){return I(e)&&P(e)==="[object Date]"}r(K,"isDate");function P(e){return Object.prototype.toString.call(e)}r(P,"objectToString");function at(e){let t={};return e.forEach(function(i,u){t[i]=!0}),t}r(at,"arrayToHash");function lt(e,t,i,u,a){let g=[];for(let o=0,l=t.length;o<l;++o)ne(t,String(o))?g.push(j(e,t,i,u,String(o),!0)):g.push("");return a.forEach(function(o){o.match(/^\d+$/)||g.push(j(e,t,i,u,o,!0))}),g}r(lt,"formatArray");function _(e){return"["+Error.prototype.toString.call(e)+"]"}r(_,"formatError");function O(e,t,i){if(e.customInspect&&t&&v(t.inspect)&&t.inspect!==y&&!(t.constructor&&t.constructor.prototype===t)){let h=t.inspect(i,e);return ee(h)||(h=O(e,h,i)),h}let u=gt(e,t);if(u)return u;let a=Object.keys(t),g=at(a);try{e.showHidden&&Object.getOwnPropertyNames&&(a=Object.getOwnPropertyNames(t))}catch{}if(T(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return _(t);if(a.length===0){if(v(t)){let h=t.name?": "+t.name:"";return e.stylize("[Function"+h+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(K(t))return e.stylize(Date.prototype.toString.call(t),"date");if(T(t))return _(t)}let o="",l=!1,f=["{","}"];if(Array.isArray(t)&&(l=!0,f=["[","]"]),v(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(o=" "+RegExp.prototype.toString.call(t)),K(t)&&(o=" "+Date.prototype.toUTCString.call(t)),T(t)&&(o=" "+_(t)),a.length===0&&(!l||t.length==0))return f[0]+o+f[1];if(i<0)return x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let p;return l?p=lt(e,t,i,g,a):p=a.map(function(h){return j(e,t,i,g,h,l)}),e.seen.pop(),ft(p,o,f)}r(O,"formatValue");function j(e,t,i,u,a,g){let o,l,f;f={value:void 0};try{f.value=t[a]}catch{}try{Object.getOwnPropertyDescriptor&&(f=Object.getOwnPropertyDescriptor(t,a)||f)}catch{}if(f.get?f.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):f.set&&(l=e.stylize("[Setter]","special")),ne(u,a)||(o="["+a+"]"),l||(e.seen.indexOf(f.value)<0?(te(i)?l=O(e,f.value,null):l=O(e,f.value,i-1),l.indexOf(`
27
27
  `)>-1&&(g?l=l.split(`
28
28
  `).map(function(p){return" "+p}).join(`
@@ -33,4 +33,4 @@ import{a as E}from"./chunk-HAXIE4MQ.js";import{a as r,b as R,c as he}from"./chun
33
33
  `)>=0&&u++,g+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?i[0]+(t===""?"":t+`
34
34
  `)+" "+e.join(`,
35
35
  `)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}r(ft,"reduceToSingleString")});var ie=R(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.format=void 0;var ht=X(),pt=re(),dt=r((e,...t)=>(0,ht.format)(pt.inspect,e,t),"format");z.format=dt});var se=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var bt=V(),mt=ie(),A=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,bt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let a=Date.now()-(this.last||Date.now());i=(0,mt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${a}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=A;var N=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function oe(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(oe,"extract");var C;function yt(e){e||(e=[]),typeof e=="string"&&(e=oe(e)),C=new N(e)}r(yt,"withoutEnv");m.withoutEnv=yt;function wt(e){let t=globalThis.DEBUG;C||(C=new N(oe(t)));let i=new A(C,e);return C.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}r(wt,"debug");m.debug=wt});var H=class extends Error{static{r(this,"SystemError")}constructor(t,i){super(t,i),this.name="InternalError"}},d=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends d{static{r(this,"ConfigurationError")}constructor(t,i){super(t,i),this.name="ConfigurationError"}},k=class extends d{static{r(this,"FeatureNotEnabledError")}constructor(t,i){super(t,i),this.name="FeatureNotEnabledError"}};var ue=he(se());var w=(0,ue.debug)("zuplo:runtime:external-service");function Rt(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=E.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}r(Rt,"getServiceAuth");async function ae(e,t){let i=Rt();if(i)if(w(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),a=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let l;if(i.customServiceMapping&&i.customServiceMapping[a])l=`https://${i.customServiceMapping[a]}`;else if(E.instance.useLegacyServiceRouting)l=`https://${a}.zuptunnel.com`;else{w("Using sha256 service routing");let h=E.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)l=`https://${await Ct(a,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw w("Cannot use sha256 service routing, missing build variables"),new d("Failed to generate fully qualified tunnel url.")}let f=new URL(`${l}${u.pathname}${u.search}`);w(`Calling external service: ${f.toString()}`);let p=await M.fetch(f.toString(),g);if(p.status===403&&p.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:l}),new d("Could not connect to secure tunnel.");return p}else throw w("Cannot call external service with Request object"),new d("Currently, we only support fetch(<some_string>, ...).");else throw w("There is no external service auth configured for this zup."),new d("There are no external services configured for this zup.")}r(ae,"externalServiceHandler");async function Ct(e,t,i,u){let a=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),l=Et(u);w(`Hashing service name: ${g}-${a}.${g}-${o}-${l}`);let f=await ce(`${g}-${a}`),p=await ce(`${g}-${o}-${l}`);return`${f}.${p}`}r(Ct,"hashServiceName");async function ce(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(ce,"hashSegment");function Et(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(Et,"sanitizeEnvironmentType");var ge=new Map;ge.set("service:",ae);var le=globalThis.fetch;function U(e,t){let i=St(t);if(typeof e=="string"){let u=new URL(e),a=ge.get(u.protocol);return a?a(e,i):le(e,i)}else return le(e,i)}r(U,"internalFetch");globalThis.fetch=U;var St=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Ot={fetch:U},M=Ot;var fe=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{r(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let i=await M.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!i.ok)throw new Error(`Request to PDP service failed with response status ${i.status}.`);return await i.json()}};export{se as a,H as b,d as c,q as d,k as e,M as f,fe as g};
36
- /*! For license information please see chunk-BUNYKRVW.js.LEGAL.txt */
36
+ /*! For license information please see chunk-OHZWUPN3.js.LEGAL.txt */
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a}from"./chunk-HAXIE4MQ.js";import{a as n}from"./chunk-PPV7V43C.js";var c=(o=>(o.Build="build-data",o.CorsPreflight="cors-preflight",o.DeveloperPortal="developer-portal",o.DeveloperPortalLegacy="developer-portal-legacy",o.StripePlugin="stripe-plugin",o.EmptyGatewayCatchall="empty-gateway-catchall",o.Ping="ping",o.UnmatchedPath="unmatched-path",o))(c||{});var p=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function _(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!p.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}n(_,"isRestrictedEnvVariableName");function g(e){return!!e.startsWith("ZUPLO_")}n(g,"isZuploReadableEnvVariableName");var f=new Proxy({},{get(e,r){let t=String(r);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return a.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return a.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return a.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return a.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return a.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return a.instance.build.BUILD_ID}if(!(_(t)&&!g(t)))return a.instance.runtime[t]}});function C(e,r,t){return`_${s(e+"_"+r+"_"+t)}`}n(C,"getRawOperationDataIdentifierName");function h(e,r,t,i){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+"_"+t.toLowerCase()+`_${i.toLowerCase()}`}n(h,"getIdForParameterSchema");function A(e,r,t){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+`_rb_${s(t.toLowerCase())}`}n(A,"getIdForRequestBodySchema");function m(e,r){return`_${s(e)}__${s(r)}`}n(m,"getIdForRefSchema");function s(e){let r=[];for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122?r.push(e.charAt(t)):r.push("_")}return r.join("")}n(s,"sanitizedIdentifierName");export{c as a,_ as b,g as c,f as d,C as e,h as f,A as g,m as h,s as i};
26
- /*! For license information please see chunk-W2THI7KO.js.LEGAL.txt */
25
+ import{a}from"./chunk-NFVGBDMC.js";import{a as n}from"./chunk-PPV7V43C.js";var c=(o=>(o.Build="build-data",o.CorsPreflight="cors-preflight",o.DeveloperPortal="developer-portal",o.DeveloperPortalLegacy="developer-portal-legacy",o.StripePlugin="stripe-plugin",o.EmptyGatewayCatchall="empty-gateway-catchall",o.Ping="ping",o.UnmatchedPath="unmatched-path",o))(c||{});var p=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function _(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!p.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}n(_,"isRestrictedEnvVariableName");function g(e){return!!e.startsWith("ZUPLO_")}n(g,"isZuploReadableEnvVariableName");var f=new Proxy({},{get(e,r){let t=String(r);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return a.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return a.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return a.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return a.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return a.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return a.instance.build.BUILD_ID}if(!(_(t)&&!g(t)))return a.instance.runtime[t]}});function C(e,r,t){return`_${s(e+"_"+r+"_"+t)}`}n(C,"getRawOperationDataIdentifierName");function h(e,r,t,i){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+"_"+t.toLowerCase()+`_${i.toLowerCase()}`}n(h,"getIdForParameterSchema");function A(e,r,t){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+`_rb_${s(t.toLowerCase())}`}n(A,"getIdForRequestBodySchema");function m(e,r){return`_${s(e)}__${s(r)}`}n(m,"getIdForRefSchema");function s(e){let r=[];for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122?r.push(e.charAt(t)):r.push("_")}return r.join("")}n(s,"sanitizedIdentifierName");export{c as a,_ as b,g as c,f as d,C as e,h as f,A as g,m as h,s as i};
26
+ /*! For license information please see chunk-VLX2J7HF.js.LEGAL.txt */