@zuplo/runtime 5.2329.0 → 5.2331.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 +1 -1
- package/out/cjs/internal/index.js +1 -1
- package/out/cjs/policies/axiomatics-authz-inbound/exports.js +4 -4
- package/out/esm/{chunk-KKIQMPVP.js → chunk-DCA73QUZ.js} +2 -2
- package/out/esm/{chunk-FYAUORKR.js → chunk-DV6LG6L2.js} +2 -2
- package/out/esm/{chunk-ZRDXIUWC.js → chunk-TC3FNLPZ.js} +2 -2
- package/out/esm/index.js +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/policies/axiomatics-authz-inbound/exports.js +1 -1
- package/package.json +1 -1
- /package/out/esm/{chunk-FYAUORKR.js.LEGAL.txt → chunk-DCA73QUZ.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-KKIQMPVP.js.LEGAL.txt → chunk-DV6LG6L2.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-ZRDXIUWC.js.LEGAL.txt → chunk-TC3FNLPZ.js.LEGAL.txt} +0 -0
package/out/cjs/index.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
`))):u=n.stylize("[Circular]","special")),Ki(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(zr,"formatProperty");function vl(n,e){if(Ki(e))return n.stylize("undefined","undefined");if(Ji(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(xl(e))return n.stylize(""+e,"number");if(Il(e))return n.stylize(""+e,"boolean");if(Yi(e))return n.stylize("null","null")}i(vl,"formatPrimitive");function Cl(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(Cl,"reduceToSingleString")});var es=$t(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.format=void 0;var Sl=Gi(),Al=Qi(),_l=i((n,...e)=>(0,Sl.format)(Al.inspect,n,e),"format");mn.format=_l});var qe=$t(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.debug=Ge.withoutEnv=Ge.Debugger=void 0;var Ll=Vi(),kl=es(),gn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Ll.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,kl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ge.Debugger=gn;var fn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ts(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(ts,"extract");var jt;function Nl(n){n||(n=[]),typeof n=="string"&&(n=ts(n)),jt=new fn(n)}i(Nl,"withoutEnv");Ge.withoutEnv=Nl;function Ml(n){let e=globalThis.DEBUG;jt||(jt=new fn(ts(e)));let t=new gn(jt,n);return jt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Ml,"debug");Ge.debug=Ml});var Gp={};Cc(Gp,{AWSLoggingPlugin:()=>tr,AmberfloMeteringInboundPolicy:()=>Va,AmberfloMeteringPolicy:()=>ur,ApiAuthKeyInboundPolicy:()=>Ka,ApiKeyInboundPolicy:()=>lr,AuditLogDataStaxProvider:()=>or,AuditLogPlugin:()=>ir,Auth0JwtInboundPolicy:()=>Xa,AwsLambdaHandlerExtensions:()=>Oa,AxiomaticsAuthZInboundPolicy:()=>mr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>Qa,BasicRateLimitInboundPolicy:()=>Oi,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>hr,CachingInboundPolicy:()=>tu,ChangeMethodInboundPolicy:()=>nu,ClearHeadersInboundPolicy:()=>ru,ClearHeadersOutboundPolicy:()=>ou,ClerkJwtInboundPolicy:()=>iu,CognitoJwtInboundPolicy:()=>su,ComplexRateLimitInboundPolicy:()=>Ir,CompositeInboundPolicy:()=>du,ConfigurationError:()=>g,ContentTypes:()=>En,ContextData:()=>he,CryptoBeta:()=>Mr,CurityPhantomTokenInboundPolicy:()=>pu,DataDogLoggingPlugin:()=>$n,DataDogMetricsPlugin:()=>nr,DynaTraceLoggingPlugin:()=>Yn,DynatraceMetricsPlugin:()=>rr,FirebaseJwtInboundPolicy:()=>mu,FormDataToJsonInboundPolicy:()=>gu,GeoFilterInboundPolicy:()=>fu,GoogleCloudLoggingPlugin:()=>Zn,Handler:()=>Kn,HttpProblems:()=>x,HttpStatusCode:()=>Wt,InboundPolicy:()=>fe,JWTScopeValidationInboundPolicy:()=>hu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>Xn,LookupResult:()=>It,MemoryZoneReadThroughCache:()=>ae,MockApiInboundPolicy:()=>bu,MoesifInboundPolicy:()=>xu,MonetizationInboundPolicy:()=>xr,OktaFGAAuthZInboundPolicy:()=>Or,OktaJwtInboundPolicy:()=>Nu,OpenFGAAuthZInboundPolicy:()=>vr,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Ke,PropelAuthJwtInboundPolicy:()=>Du,RateLimitInboundPolicy:()=>Oi,ReadmeMetricsInboundPolicy:()=>Bu,RemoveHeadersInboundPolicy:()=>zu,RemoveHeadersOutboundPolicy:()=>Vu,RemoveQueryParamsInboundPolicy:()=>Gu,ReplaceStringOutboundPolicy:()=>Wu,RequestSizeLimitInboundPolicy:()=>Ju,RequestValidationInboundPolicy:()=>Si,RequireOriginInboundPolicy:()=>oc,ResponseSendingEvent:()=>ht,ResponseSentEvent:()=>yt,Router:()=>Et,RuntimeError:()=>_,SYSTEM_LOGGER:()=>zt,SchemaBasedRequestValidation:()=>rc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>ic,SetHeadersInboundPolicy:()=>sc,SetHeadersOutboundPolicy:()=>ac,SetQueryParamsInboundPolicy:()=>uc,SetStatusOutboundPolicy:()=>cc,SleepInboundPolicy:()=>lc,StripeMonetizationPlugin:()=>mi,StripeWebhookVerificationInboundPolicy:()=>vt,SumoLogicLoggingPlugin:()=>Qn,SupabaseJwtInboundPolicy:()=>dc,SystemRouteName:()=>De,TelemetryPlugin:()=>gt,UpstreamAzureAdServiceAuthInboundPolicy:()=>pc,UpstreamFirebaseAdminAuthInboundPolicy:()=>gc,UpstreamFirebaseUserAuthInboundPolicy:()=>fc,UpstreamGcpJwtInboundPolicy:()=>hc,UpstreamGcpServiceAuthInboundPolicy:()=>bc,VMWareLogInsightLoggingPlugin:()=>er,ValidateJsonSchemaInbound:()=>wc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>mt,ZuploRequest:()=>oe,awsLambdaHandler:()=>va,environment:()=>Ee,getIdForParameterSchema:()=>Cr,getIdForRefSchema:()=>Xu,getIdForRequestBodySchema:()=>Sr,getRawOperationDataIdentifierName:()=>Yu,httpStatuses:()=>On,openApiSpecHandler:()=>Ca,redirectHandler:()=>Sa,sanitizedIdentifierName:()=>tt,serialize:()=>xn,setMoesifContext:()=>Eu,trackFeature:()=>f,urlForwardHandler:()=>Aa,urlRewriteHandler:()=>_a,webSocketHandler:()=>La,webSocketPipelineHandler:()=>Ma});module.exports=Sc(Gp);var is=ze(qe());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},_=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends _{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},hn=class extends _{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wr="2024-03-14",ns=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 rs(){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:ns[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(rs,"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=rs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.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 rt=(0,is.debug)("zuplo:runtime:external-service");function Dl(){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(Dl,"getServiceAuth");async function ss(n,e){let t=Dl();if(t)if(rt(`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{rt("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Ul(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw rt("Cannot use sha256 service routing, missing build variables"),new _("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);rt(`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 _("Could not connect to secure tunnel.");return l}else throw rt("Cannot call external service with Request object"),new _("Currently, we only support fetch(<some_string>, ...).");else throw rt("There is no external service auth configured for this zup."),new _("There are no external services configured for this zup.")}i(ss,"externalServiceHandler");async function Ul(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Hl(r);rt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await os(`${s}-${o}`),l=await os(`${s}-${a}-${u}`);return`${c}.${l}`}i(Ul,"hashServiceName");async function os(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(os,"hashSegment");function Hl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Hl,"sanitizeEnvironmentType");var us=new Map;us.set("service:",ss);var as=globalThis.fetch;function Kr(n,e){let t=Zl(e);if(typeof n=="string"){let r=new URL(n),o=us.get(r.protocol);return o?o(n,t):as(n,t)}else return as(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Zl=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 ql={fetch:Kr},F=ql;Function.prototype.toString=function(){return"[native code]"};var yn=globalThis,cs=yn.caches;if(cs){let n=cs.open;yn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete yn.caches.default,Object.freeze(yn.caches)}var ls=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)})}},pt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ls.get(e);r||(r=new Jr(t),ls.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 Yr="__zuplo-expiry-header",mt=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(Yr);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(Yr,`${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(Yr,`${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 ae=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new pt(r),this.#n=new mt(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 ds="zuplo-request-id",ot="zp-rid",Xr="zp-body-removed",it="cf-ray",ps="x-real-ip",Qr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ms="cf-region",gs="cf-region-code",fs="cf-metro-code",hs="cf-postal-code",ys="cf-timezone",bs="zp-ipcity",ws="zp-ipcontinent",Rs="zp-ipcountry",Ps="zp-iplongitude",Is="zp-iplatitude",Es="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",xs=[Qr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],Ts=["zp-","cf-"],Os=[ot,it,Xr];var Bt=Symbol("zuplo_meters"),bn=Symbol("zuplo_dynamic_meters"),zt="system-logger";var da=require("@opentelemetry/api"),pa=ze(qe());var Tn=require("@opentelemetry/api");var Je=require("@opentelemetry/api");var vs=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Cs(n){vs=n}i(Cs,"setTelemetryInitFunction");var Ss=i(n=>vs(n),"proxyHandler");var We=class{static{i(this,"RuntimePlugin")}},Fe=class extends We{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},wn=class extends Fe{static{i(this,"MeteringPlugin")}},gt=class extends We{static{i(this,"TelemetryPlugin")}};var Rn=new Set,As=new Set;function f(n){As.has(n)||(As.add(n),Rn.add(n))}i(f,"trackFeature");function _s(){let n=[...Rn];return Rn.clear(),n}i(_s,"getUnsentFeatures");function Ls(n){for(let e of n)Rn.add(e)}i(Ls,"restoreFeatures");var Vt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new _("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ke=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Vt.problemResponseFormat(e,t,r)}};function Pn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Pn(t)}return Object.freeze(n)}i(Pn,"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 Pn(this.#e)}get params(){return Pn(this.#t)}user};var Gt={},$e=[],mo=[],go=[],fo=[];var In={addPlugin(n){$e.push(n)},addRequestHook(n){mo.push(n)},addResponseSendingHook(n){go.push(n)},addResponseSendingFinalHook(n){fo.push(n)}},Ns=i(async(n,e)=>{if(mo.length===0)return n;let t=Je.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 g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ms=i(async(n,e,t)=>{if(go.length===0)return n;let r=Je.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 g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ds=i(async(n,e,t)=>{if(fo.length===0)return;let r=Je.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:Je.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ks=!1;async function Us(n){if(!ks){n&&(f("runtime.extensions"),await n(In)),Gt.value=In;for(let e of $e)if(e instanceof gt){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});Cs(t)}for(let e of $e)e instanceof Fe&&await e.initialize(In);Vt.setProblemResponseFormat(In.problemResponseFormat),ks=!0}}i(Us,"initializeRuntime");var En={Json:"application/json",Form:"application/x-www-form-urlencoded"};function xn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(En.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(En.Json)||!e?JSON.stringify(n):n}i(xn,"serialize");function ft(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(ft,"isSystemRoute");var ge=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Tn.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:Tn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async B=>{let q=await r(B,s);return Fl(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ft(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ht(o,l);s.dispatchEvent(p);let h=Pe.getContextExtensions(s),y=h.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await h.onResponseSending(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Ms(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new yt(o,A));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Ds(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Fl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(xn(n),{headers:{"content-type":"application/json"}})}i(Fl,"resultToResponse");var Wt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Wt||{}),Hs={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 $l={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"},On=$l;function jl(n){return`${new URL(n.url).pathname}`}i(jl,"instance");function Bl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(it);return r&&(t.rayId=r),t}i(Bl,"trace");var zl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:jl(e),trace:Bl(e,t),...r},additionalHeaders:o,statusText:On[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Hs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=zl(this.getProblemFromStatus(e),t,r,o,s);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ye=class extends We{static{i(this,"MetricsPlugin")}};var ee=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 Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var vn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,ee.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=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=_s(),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();ee.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ls(u)}}};var ce=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=Kt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Kt={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(it)??void 0,c=n.headers.get(Es)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new vn(e)),$e.forEach(A=>{if(A instanceof Ye){let P=A.getTransport();y.push(P)}}),y.forEach(A=>{A.pushMetrics(h,e)}),a},"metricsProcessor");var De=(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))(De||{});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"&&ee.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ge({processors:[Ie],handler:t,gateway:e}),o=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Vl}=Object.prototype,{propertyIsEnumerable:Gl}=Object.prototype;function bo(n){return Vl.call(n)}i(bo,"toString");function Oe(n){return typeof n=="string"}i(Oe,"isString");function bt(n){return Oe(n)&&n!==""}i(bt,"isNonEmptyString");function Zs(n){return bo(n)==="[object RegExp]"}i(Zs,"isRegexp");function qs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Gl.call(n,e))]}i(qs,"getOwnEnumerableKeys");function st(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(st,"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 Fs(n){return typeof n>"u"}i(Fs,"isUndefined");function $s(n){return Fs(n)||n===null}i($s,"isUndefinedOrNull");function Jt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Jt,"isErrorLike");var js=new Map;function wt(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=js.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 js.set(n,r),r}i(wt,"statusCodesStringToNumberArray");function at(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new _(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(at,"getValueFromRequestUser");function ut(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("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 g(`Expected type of string, received type '${typeof n}'`)}i(ut,"parseValueToStringArray");function Bs(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!st(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!bt(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new g(`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 g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Po(t,"allowedHeaders"),o=Po(t,"allowedMethods"),s=Po(t,"exposeHeaders"),a;try{a=ut(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(Bs,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=ut(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Po,"parseOptionalProperty");var Cn=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"),Sn=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 h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,A=Wl(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new ge({processors:[Ie],handler:r,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Wl=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 g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Cn(a.allowedOrigins,t);return u?{isValid:!0,headers:Sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ge({processors:[Ie],handler:t,gateway:e}),o=new ce({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 ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Vs=i((n,e)=>{let t=i(async(o,s)=>{let a=Gt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new ge({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var Kl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gs=i(n=>{Kl.forEach(e=>n.delete(e))},"stripCorsHeaders"),An=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 Gs(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 Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Jl(o,t.routeData.corsPolicies),u=Yl(n,a),c=new Headers(s.headers);return Gs(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"),Jl=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 g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Yl=i((n,e)=>{let t=Cn(e.allowedOrigins,n.headers.get("origin"));return t?Sn(e,t):{}},"getCorsHeaders");var xo=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 ge({processors:[An],handler:t,gateway:e}),o=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var Rt=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 _n=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Oe(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},fe=class extends _n{static{i(this,"InboundPolicy")}},je=class extends _n{static{i(this,"OutboundPolicy")}};var vo=class extends fe{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)}},To=new Map;function Yt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!To.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`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 g(`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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof fe)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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);To.set(a.name,c)}),t.map(s=>{let a=To.get(s);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}i(Yt,"getInboundPolicyInstances");var Oo=new Map;function Xl(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 g(`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 g(`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 g(`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 g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`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 _("Internal error. Policy not found in cache.");return s})}i(Xl,"getOutboundPolicyInstances");var So=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Rt.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 h=new g(`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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}});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"),Ql=i(n=>async(e,t,r)=>{let o=Rt.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 h=new g(`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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Ln=i(async(n,e,t,r)=>{let o=Yt(e.route,t.routeData.policies),s=Xl(e.route,t.routeData.policies);return Ks({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ws({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ks({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ws,"createInternalPolicyProcessor");async function Ks({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=Ql(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(Ks,"executePolicyProcessor");function Js(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ed,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]=td(l,o)}s=u+1}return t}i(Js,"parse");function ed(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ed,"decode");function td(n,e){try{return e(n)}catch{return n}}i(td,"tryDecode");function Ys(n,e){try{let t=/v\d+(-\d+)?/g,o=Js(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Ys,"devPortalBaseURL");var Xs="/__zuplo/dev-portal",nd="dev-portal-id",rd="dev-portal-host",od="zp-account",id="zp-project",sd="dev-portal-build",ad=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Cl,"reduceToSingleString")});var es=$t(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.format=void 0;var Sl=Gi(),Al=Qi(),_l=i((n,...e)=>(0,Sl.format)(Al.inspect,n,e),"format");mn.format=_l});var qe=$t(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.debug=Ge.withoutEnv=Ge.Debugger=void 0;var Ll=Vi(),kl=es(),gn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Ll.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,kl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ge.Debugger=gn;var fn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ts(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(ts,"extract");var jt;function Nl(n){n||(n=[]),typeof n=="string"&&(n=ts(n)),jt=new fn(n)}i(Nl,"withoutEnv");Ge.withoutEnv=Nl;function Ml(n){let e=globalThis.DEBUG;jt||(jt=new fn(ts(e)));let t=new gn(jt,n);return jt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Ml,"debug");Ge.debug=Ml});var Gp={};Cc(Gp,{AWSLoggingPlugin:()=>tr,AmberfloMeteringInboundPolicy:()=>Va,AmberfloMeteringPolicy:()=>ur,ApiAuthKeyInboundPolicy:()=>Ka,ApiKeyInboundPolicy:()=>lr,AuditLogDataStaxProvider:()=>or,AuditLogPlugin:()=>ir,Auth0JwtInboundPolicy:()=>Xa,AwsLambdaHandlerExtensions:()=>Oa,AxiomaticsAuthZInboundPolicy:()=>mr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>Qa,BasicRateLimitInboundPolicy:()=>Oi,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>hr,CachingInboundPolicy:()=>tu,ChangeMethodInboundPolicy:()=>nu,ClearHeadersInboundPolicy:()=>ru,ClearHeadersOutboundPolicy:()=>ou,ClerkJwtInboundPolicy:()=>iu,CognitoJwtInboundPolicy:()=>su,ComplexRateLimitInboundPolicy:()=>Ir,CompositeInboundPolicy:()=>du,ConfigurationError:()=>g,ContentTypes:()=>En,ContextData:()=>he,CryptoBeta:()=>Mr,CurityPhantomTokenInboundPolicy:()=>pu,DataDogLoggingPlugin:()=>$n,DataDogMetricsPlugin:()=>nr,DynaTraceLoggingPlugin:()=>Yn,DynatraceMetricsPlugin:()=>rr,FirebaseJwtInboundPolicy:()=>mu,FormDataToJsonInboundPolicy:()=>gu,GeoFilterInboundPolicy:()=>fu,GoogleCloudLoggingPlugin:()=>Zn,Handler:()=>Kn,HttpProblems:()=>x,HttpStatusCode:()=>Wt,InboundPolicy:()=>fe,JWTScopeValidationInboundPolicy:()=>hu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>Xn,LookupResult:()=>It,MemoryZoneReadThroughCache:()=>ae,MockApiInboundPolicy:()=>bu,MoesifInboundPolicy:()=>xu,MonetizationInboundPolicy:()=>xr,OktaFGAAuthZInboundPolicy:()=>Or,OktaJwtInboundPolicy:()=>Nu,OpenFGAAuthZInboundPolicy:()=>vr,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Ke,PropelAuthJwtInboundPolicy:()=>Du,RateLimitInboundPolicy:()=>Oi,ReadmeMetricsInboundPolicy:()=>Bu,RemoveHeadersInboundPolicy:()=>zu,RemoveHeadersOutboundPolicy:()=>Vu,RemoveQueryParamsInboundPolicy:()=>Gu,ReplaceStringOutboundPolicy:()=>Wu,RequestSizeLimitInboundPolicy:()=>Ju,RequestValidationInboundPolicy:()=>Si,RequireOriginInboundPolicy:()=>oc,ResponseSendingEvent:()=>ht,ResponseSentEvent:()=>yt,Router:()=>Et,RuntimeError:()=>_,SYSTEM_LOGGER:()=>zt,SchemaBasedRequestValidation:()=>rc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>ic,SetHeadersInboundPolicy:()=>sc,SetHeadersOutboundPolicy:()=>ac,SetQueryParamsInboundPolicy:()=>uc,SetStatusOutboundPolicy:()=>cc,SleepInboundPolicy:()=>lc,StripeMonetizationPlugin:()=>mi,StripeWebhookVerificationInboundPolicy:()=>vt,SumoLogicLoggingPlugin:()=>Qn,SupabaseJwtInboundPolicy:()=>dc,SystemRouteName:()=>De,TelemetryPlugin:()=>gt,UpstreamAzureAdServiceAuthInboundPolicy:()=>pc,UpstreamFirebaseAdminAuthInboundPolicy:()=>gc,UpstreamFirebaseUserAuthInboundPolicy:()=>fc,UpstreamGcpJwtInboundPolicy:()=>hc,UpstreamGcpServiceAuthInboundPolicy:()=>bc,VMWareLogInsightLoggingPlugin:()=>er,ValidateJsonSchemaInbound:()=>wc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>mt,ZuploRequest:()=>oe,awsLambdaHandler:()=>va,environment:()=>Ee,getIdForParameterSchema:()=>Cr,getIdForRefSchema:()=>Xu,getIdForRequestBodySchema:()=>Sr,getRawOperationDataIdentifierName:()=>Yu,httpStatuses:()=>On,openApiSpecHandler:()=>Ca,redirectHandler:()=>Sa,sanitizedIdentifierName:()=>tt,serialize:()=>xn,setMoesifContext:()=>Eu,trackFeature:()=>f,urlForwardHandler:()=>Aa,urlRewriteHandler:()=>_a,webSocketHandler:()=>La,webSocketPipelineHandler:()=>Ma});module.exports=Sc(Gp);var is=ze(qe());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},_=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends _{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},hn=class extends _{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wr="2024-03-14",ns=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 rs(){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:ns[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(rs,"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=rs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get 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 rt=(0,is.debug)("zuplo:runtime:external-service");function Dl(){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(Dl,"getServiceAuth");async function ss(n,e){let t=Dl();if(t)if(rt(`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{rt("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Ul(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw rt("Cannot use sha256 service routing, missing build variables"),new _("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);rt(`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 _("Could not connect to secure tunnel.");return l}else throw rt("Cannot call external service with Request object"),new _("Currently, we only support fetch(<some_string>, ...).");else throw rt("There is no external service auth configured for this zup."),new _("There are no external services configured for this zup.")}i(ss,"externalServiceHandler");async function Ul(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Hl(r);rt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await os(`${s}-${o}`),l=await os(`${s}-${a}-${u}`);return`${c}.${l}`}i(Ul,"hashServiceName");async function os(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(os,"hashSegment");function Hl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Hl,"sanitizeEnvironmentType");var us=new Map;us.set("service:",ss);var as=globalThis.fetch;function Kr(n,e){let t=Zl(e);if(typeof n=="string"){let r=new URL(n),o=us.get(r.protocol);return o?o(n,t):as(n,t)}else return as(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Zl=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 ql={fetch:Kr},F=ql;Function.prototype.toString=function(){return"[native code]"};var yn=globalThis,cs=yn.caches;if(cs){let n=cs.open;yn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete yn.caches.default,Object.freeze(yn.caches)}var ls=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)})}},pt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ls.get(e);r||(r=new Jr(t),ls.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 Yr="__zuplo-expiry-header",mt=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(Yr);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(Yr,`${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(Yr,`${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 ae=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new pt(r),this.#n=new mt(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 ds="zuplo-request-id",ot="zp-rid",Xr="zp-body-removed",it="cf-ray",ps="x-real-ip",Qr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ms="cf-region",gs="cf-region-code",fs="cf-metro-code",hs="cf-postal-code",ys="cf-timezone",bs="zp-ipcity",ws="zp-ipcontinent",Rs="zp-ipcountry",Ps="zp-iplongitude",Is="zp-iplatitude",Es="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",xs=[Qr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],Ts=["zp-","cf-"],Os=[ot,it,Xr];var Bt=Symbol("zuplo_meters"),bn=Symbol("zuplo_dynamic_meters"),zt="system-logger";var da=require("@opentelemetry/api"),pa=ze(qe());var Tn=require("@opentelemetry/api");var Je=require("@opentelemetry/api");var vs=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Cs(n){vs=n}i(Cs,"setTelemetryInitFunction");var Ss=i(n=>vs(n),"proxyHandler");var We=class{static{i(this,"RuntimePlugin")}},Fe=class extends We{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},wn=class extends Fe{static{i(this,"MeteringPlugin")}},gt=class extends We{static{i(this,"TelemetryPlugin")}};var Rn=new Set,As=new Set;function f(n){As.has(n)||(As.add(n),Rn.add(n))}i(f,"trackFeature");function _s(){let n=[...Rn];return Rn.clear(),n}i(_s,"getUnsentFeatures");function Ls(n){for(let e of n)Rn.add(e)}i(Ls,"restoreFeatures");var Vt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new _("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ke=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Vt.problemResponseFormat(e,t,r)}};function Pn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Pn(t)}return Object.freeze(n)}i(Pn,"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 Pn(this.#e)}get params(){return Pn(this.#t)}user};var Gt={},$e=[],mo=[],go=[],fo=[];var In={addPlugin(n){$e.push(n)},addRequestHook(n){mo.push(n)},addResponseSendingHook(n){go.push(n)},addResponseSendingFinalHook(n){fo.push(n)}},Ns=i(async(n,e)=>{if(mo.length===0)return n;let t=Je.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 g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ms=i(async(n,e,t)=>{if(go.length===0)return n;let r=Je.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 g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ds=i(async(n,e,t)=>{if(fo.length===0)return;let r=Je.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:Je.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ks=!1;async function Us(n){if(!ks){n&&(f("runtime.extensions"),await n(In)),Gt.value=In;for(let e of $e)if(e instanceof gt){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});Cs(t)}for(let e of $e)e instanceof Fe&&await e.initialize(In);Vt.setProblemResponseFormat(In.problemResponseFormat),ks=!0}}i(Us,"initializeRuntime");var En={Json:"application/json",Form:"application/x-www-form-urlencoded"};function xn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(En.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(En.Json)||!e?JSON.stringify(n):n}i(xn,"serialize");function ft(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(ft,"isSystemRoute");var ge=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Tn.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:Tn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async B=>{let q=await r(B,s);return Fl(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ft(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ht(o,l);s.dispatchEvent(p);let h=Pe.getContextExtensions(s),y=h.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await h.onResponseSending(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Ms(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new yt(o,A));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Ds(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Fl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(xn(n),{headers:{"content-type":"application/json"}})}i(Fl,"resultToResponse");var Wt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Wt||{}),Hs={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 $l={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"},On=$l;function jl(n){return`${new URL(n.url).pathname}`}i(jl,"instance");function Bl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(it);return r&&(t.rayId=r),t}i(Bl,"trace");var zl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:jl(e),trace:Bl(e,t),...r},additionalHeaders:o,statusText:On[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Hs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=zl(this.getProblemFromStatus(e),t,r,o,s);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ye=class extends We{static{i(this,"MetricsPlugin")}};var ee=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 Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var vn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,ee.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=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=_s(),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();ee.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ls(u)}}};var ce=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=Kt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Kt={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(it)??void 0,c=n.headers.get(Es)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new vn(e)),$e.forEach(A=>{if(A instanceof Ye){let P=A.getTransport();y.push(P)}}),y.forEach(A=>{A.pushMetrics(h,e)}),a},"metricsProcessor");var De=(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))(De||{});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"&&ee.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ge({processors:[Ie],handler:t,gateway:e}),o=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Vl}=Object.prototype,{propertyIsEnumerable:Gl}=Object.prototype;function bo(n){return Vl.call(n)}i(bo,"toString");function Oe(n){return typeof n=="string"}i(Oe,"isString");function bt(n){return Oe(n)&&n!==""}i(bt,"isNonEmptyString");function Zs(n){return bo(n)==="[object RegExp]"}i(Zs,"isRegexp");function qs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Gl.call(n,e))]}i(qs,"getOwnEnumerableKeys");function st(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(st,"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 Fs(n){return typeof n>"u"}i(Fs,"isUndefined");function $s(n){return Fs(n)||n===null}i($s,"isUndefinedOrNull");function Jt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Jt,"isErrorLike");var js=new Map;function wt(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=js.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 js.set(n,r),r}i(wt,"statusCodesStringToNumberArray");function at(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new _(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(at,"getValueFromRequestUser");function ut(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("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 g(`Expected type of string, received type '${typeof n}'`)}i(ut,"parseValueToStringArray");function Bs(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!st(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!bt(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new g(`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 g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Po(t,"allowedHeaders"),o=Po(t,"allowedMethods"),s=Po(t,"exposeHeaders"),a;try{a=ut(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(Bs,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=ut(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Po,"parseOptionalProperty");var Cn=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"),Sn=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 h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,A=Wl(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new ge({processors:[Ie],handler:r,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Wl=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 g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Cn(a.allowedOrigins,t);return u?{isValid:!0,headers:Sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ge({processors:[Ie],handler:t,gateway:e}),o=new ce({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 ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Vs=i((n,e)=>{let t=i(async(o,s)=>{let a=Gt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new ge({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var Kl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gs=i(n=>{Kl.forEach(e=>n.delete(e))},"stripCorsHeaders"),An=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 Gs(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 Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Jl(o,t.routeData.corsPolicies),u=Yl(n,a),c=new Headers(s.headers);return Gs(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"),Jl=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 g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Yl=i((n,e)=>{let t=Cn(e.allowedOrigins,n.headers.get("origin"));return t?Sn(e,t):{}},"getCorsHeaders");var xo=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 ge({processors:[An],handler:t,gateway:e}),o=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var Rt=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 _n=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Oe(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},fe=class extends _n{static{i(this,"InboundPolicy")}},je=class extends _n{static{i(this,"OutboundPolicy")}};var vo=class extends fe{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)}},To=new Map;function Yt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!To.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`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 g(`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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof fe)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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);To.set(a.name,c)}),t.map(s=>{let a=To.get(s);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}i(Yt,"getInboundPolicyInstances");var Oo=new Map;function Xl(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 g(`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 g(`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 g(`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 g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`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 _("Internal error. Policy not found in cache.");return s})}i(Xl,"getOutboundPolicyInstances");var So=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Rt.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 h=new g(`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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}});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"),Ql=i(n=>async(e,t,r)=>{let o=Rt.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 h=new g(`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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Ln=i(async(n,e,t,r)=>{let o=Yt(e.route,t.routeData.policies),s=Xl(e.route,t.routeData.policies);return Ks({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ws({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ks({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ws,"createInternalPolicyProcessor");async function Ks({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=Ql(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(Ks,"executePolicyProcessor");function Js(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ed,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]=td(l,o)}s=u+1}return t}i(Js,"parse");function ed(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ed,"decode");function td(n,e){try{return e(n)}catch{return n}}i(td,"tryDecode");function Ys(n,e){try{let t=/v\d+(-\d+)?/g,o=Js(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Ys,"devPortalBaseURL");var Xs="/__zuplo/dev-portal",nd="dev-portal-id",rd="dev-portal-host",od="zp-account",id="zp-project",sd="dev-portal-build",ad=`
|
|
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
|
|
25
|
+
"use strict";var u=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});var h=(e,t)=>{for(var n in t)u(e,n,{get:t[n],enumerable:!0})},R=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of f(t))!P.call(e,s)&&s!==n&&u(e,s,{get:()=>t[s],enumerable:!(i=E(t,s))||i.enumerable});return e};var U=e=>R(u({},"__esModule",{value:!0}),e);var T={};h(T,{getIdForParameterSchema:()=>p,getIdForRefSchema:()=>O,getIdForRequestBodySchema:()=>L,getRawOperationDataIdentifierName:()=>m,isRestrictedEnvVariableName:()=>l,isZuploReadableEnvVariableName:()=>g,sanitizedIdentifierName:()=>a});module.exports=U(T);var _="2024-03-14",d=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 c(){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(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:_,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:d[_]},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:""}})}r(c,"getMockEnvironment");var o=class e{static{r(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=c()),this.#e}constructor({build:t,runtime:n}){let i;try{if(n.__ZUPLO_CONFIG){let s=atob(n.__ZUPLO_CONFIG);i=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=i??{},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 managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get 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 I=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!I.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}r(l,"isRestrictedEnvVariableName");function g(e){return!!e.startsWith("ZUPLO_")}r(g,"isZuploReadableEnvVariableName");var x=new Proxy({},{get(e,t){let n=String(t);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID}if(!(l(n)&&!g(n)))return o.instance.runtime[n]}});function m(e,t,n){return`_${a(e+"_"+t+"_"+n)}`}r(m,"getRawOperationDataIdentifierName");function p(e,t,n,i){return`_${a(e.toLowerCase())}_`+t.toLowerCase()+"_"+n.toLowerCase()+`_${i.toLowerCase()}`}r(p,"getIdForParameterSchema");function L(e,t,n){return`_${a(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${a(n.toLowerCase())}`}r(L,"getIdForRequestBodySchema");function O(e,t){return`_${a(e)}__${a(t)}`}r(O,"getIdForRefSchema");function a(e){let t=[];for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i>="0".charCodeAt(0)&&i<="9".charCodeAt(0)||i>="A".charCodeAt(0)&&i<="Z".charCodeAt(0)||i>="a".charCodeAt(0)&&i<="z".charCodeAt(0)?t.push(e.charAt(n)):t.push("_")}return t.join("")}r(a,"sanitizedIdentifierName");
|
|
26
26
|
/*! For license information please see index.js.LEGAL.txt */
|
|
@@ -22,15 +22,15 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var pe=Object.create;var O=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var
|
|
26
|
-
`).map(a=>a.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}n(dt,"format");T.format=dt});var ie=R(
|
|
25
|
+
"use strict";var pe=Object.create;var O=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var n=(e,t)=>O(e,"name",{value:t,configurable:!0});var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ye=(e,t)=>{for(var i in t)O(e,i,{get:t[i],enumerable:!0})},$=(e,t,i,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _e(t))!Ee.call(e,s)&&s!==i&&O(e,s,{get:()=>t[s],enumerable:!(u=me(t,s))||u.enumerable});return e};var Oe=(e,t,i)=>(i=e!=null?pe(be(e)):{},$(t||!e||!e.__esModule?O(i,"default",{value:e,enumerable:!0}):i,e)),Re=e=>$(O({},"__esModule",{value:!0}),e);var X=R(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.generateColor=r.colorFunctions=r.stripColor=r.bgRgb24=r.rgb24=r.bgRgb8=r.rgb8=r.bgBrightWhite=r.bgBrightCyan=r.bgBrightMagenta=r.bgBrightBlue=r.bgBrightYellow=r.bgBrightGreen=r.bgBrightRed=r.bgBrightBlack=r.bgWhite=r.bgCyan=r.bgMagenta=r.bgBlue=r.bgYellow=r.bgGreen=r.bgRed=r.bgBlack=r.brightWhite=r.brightCyan=r.brightMagenta=r.brightBlue=r.brightYellow=r.brightGreen=r.brightRed=r.brightBlack=r.gray=r.white=r.cyan=r.magenta=r.blue=r.yellow=r.green=r.red=r.black=r.strikethrough=r.hidden=r.inverse=r.underline=r.italic=r.dim=r.bold=r.reset=r.getColorEnabled=r.setColorEnabled=void 0;var j=!0,A=!j;function Le(e){j||(A=e)}n(Le,"setColorEnabled");r.setColorEnabled=Le;function Te(){return A}n(Te,"getColorEnabled");r.getColorEnabled=Te;function c(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}n(c,"code");function l(e,t){return A?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}n(l,"run");function Pe(e){return l(e,c([0],0))}n(Pe,"reset");r.reset=Pe;function Ce(e){return l(e,c([1],22))}n(Ce,"bold");r.bold=Ce;function we(e){return l(e,c([2],22))}n(we,"dim");r.dim=we;function Se(e){return l(e,c([3],23))}n(Se,"italic");r.italic=Se;function Ie(e){return l(e,c([4],24))}n(Ie,"underline");r.underline=Ie;function Ue(e){return l(e,c([7],27))}n(Ue,"inverse");r.inverse=Ue;function Ae(e){return l(e,c([8],28))}n(Ae,"hidden");r.hidden=Ae;function Ne(e){return l(e,c([9],29))}n(Ne,"strikethrough");r.strikethrough=Ne;function ve(e){return l(e,c([30],39))}n(ve,"black");r.black=ve;function F(e){return l(e,c([31],39))}n(F,"red");r.red=F;function G(e){return l(e,c([32],39))}n(G,"green");r.green=G;function Y(e){return l(e,c([33],39))}n(Y,"yellow");r.yellow=Y;function V(e){return l(e,c([34],39))}n(V,"blue");r.blue=V;function q(e){return l(e,c([35],39))}n(q,"magenta");r.magenta=q;function W(e){return l(e,c([36],39))}n(W,"cyan");r.cyan=W;function Me(e){return l(e,c([37],39))}n(Me,"white");r.white=Me;function Be(e){return J(e)}n(Be,"gray");r.gray=Be;function J(e){return l(e,c([90],39))}n(J,"brightBlack");r.brightBlack=J;function ze(e){return l(e,c([91],39))}n(ze,"brightRed");r.brightRed=ze;function xe(e){return l(e,c([92],39))}n(xe,"brightGreen");r.brightGreen=xe;function Ze(e){return l(e,c([93],39))}n(Ze,"brightYellow");r.brightYellow=Ze;function ke(e){return l(e,c([94],39))}n(ke,"brightBlue");r.brightBlue=ke;function De(e){return l(e,c([95],39))}n(De,"brightMagenta");r.brightMagenta=De;function He(e){return l(e,c([96],39))}n(He,"brightCyan");r.brightCyan=He;function $e(e){return l(e,c([97],39))}n($e,"brightWhite");r.brightWhite=$e;function je(e){return l(e,c([40],49))}n(je,"bgBlack");r.bgBlack=je;function Fe(e){return l(e,c([41],49))}n(Fe,"bgRed");r.bgRed=Fe;function Ge(e){return l(e,c([42],49))}n(Ge,"bgGreen");r.bgGreen=Ge;function Ye(e){return l(e,c([43],49))}n(Ye,"bgYellow");r.bgYellow=Ye;function Ve(e){return l(e,c([44],49))}n(Ve,"bgBlue");r.bgBlue=Ve;function qe(e){return l(e,c([45],49))}n(qe,"bgMagenta");r.bgMagenta=qe;function We(e){return l(e,c([46],49))}n(We,"bgCyan");r.bgCyan=We;function Je(e){return l(e,c([47],49))}n(Je,"bgWhite");r.bgWhite=Je;function Xe(e){return l(e,c([100],49))}n(Xe,"bgBrightBlack");r.bgBrightBlack=Xe;function Ke(e){return l(e,c([101],49))}n(Ke,"bgBrightRed");r.bgBrightRed=Ke;function Qe(e){return l(e,c([102],49))}n(Qe,"bgBrightGreen");r.bgBrightGreen=Qe;function et(e){return l(e,c([103],49))}n(et,"bgBrightYellow");r.bgBrightYellow=et;function tt(e){return l(e,c([104],49))}n(tt,"bgBrightBlue");r.bgBrightBlue=tt;function nt(e){return l(e,c([105],49))}n(nt,"bgBrightMagenta");r.bgBrightMagenta=nt;function rt(e){return l(e,c([106],49))}n(rt,"bgBrightCyan");r.bgBrightCyan=rt;function it(e){return l(e,c([107],49))}n(it,"bgBrightWhite");r.bgBrightWhite=it;function p(e,t=255,i=0){return Math.trunc(Math.max(Math.min(e,t),i))}n(p,"clampAndTruncate");function ot(e,t){return l(e,c([38,5,p(t)],39))}n(ot,"rgb8");r.rgb8=ot;function st(e,t){return l(e,c([48,5,p(t)],49))}n(st,"bgRgb8");r.bgRgb8=st;function ut(e,t){return typeof t=="number"?l(e,c([38,2,t>>16&255,t>>8&255,t&255],39)):l(e,c([38,2,p(t.r),p(t.g),p(t.b)],39))}n(ut,"rgb24");r.rgb24=ut;function ct(e,t){return typeof t=="number"?l(e,c([48,2,t>>16&255,t>>8&255,t&255],49)):l(e,c([48,2,p(t.r),p(t.g),p(t.b)],49))}n(ct,"bgRgb24");r.bgRgb24=ct;var lt=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 at(e){return e.replace(lt,"")}n(at,"stripColor");r.stripColor=at;r.colorFunctions=[F,G,Y,V,q,W];function gt(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}n(gt,"hashCode");function ft(e){let t=Math.abs(gt(e));return r.colorFunctions[t%r.colorFunctions.length]}n(ft,"generateColor");r.generateColor=ft});var K=R(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.format=void 0;function dt(e,t,...i){let u=0,s=i.length,g=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(u>=s)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
|
+
`).map(a=>a.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}n(dt,"format");T.format=dt});var ie=R(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.inspect=void 0;function b(e,t,i,u){let s={seen:[],stylize:ht,showHidden:t??!1,depth:i??2,colors:u??!1,customInspect:!0};return s.colors&&(s.stylize=mt),P(s,e,s.depth)}n(b,"inspect");C.inspect=b;b.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]};b.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ht(e,t){return e}n(ht,"stylizeNoColor");function pt(e){return typeof e=="boolean"}n(pt,"isBoolean");function ee(e){return e===void 0}n(ee,"isUndefined");function mt(e,t){let i=b.styles[t];return i?"\x1B["+b.colors[i][0]+"m"+e+"\x1B["+b.colors[i][1]+"m":e}n(mt,"stylizeWithColor");function N(e){return typeof e=="function"}n(N,"isFunction");function te(e){return typeof e=="string"}n(te,"isString");function _t(e){return typeof e=="number"}n(_t,"isNumber");function ne(e){return e===null}n(ne,"isNull");function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}n(re,"hasOwn");function v(e){return x(e)&&Z(e)==="[object RegExp]"}n(v,"isRegExp");function x(e){return typeof e=="object"&&e!==null}n(x,"isObject");function M(e){return x(e)&&(Z(e)==="[object Error]"||e instanceof Error)}n(M,"isError");function Q(e){return x(e)&&Z(e)==="[object Date]"}n(Q,"isDate");function Z(e){return Object.prototype.toString.call(e)}n(Z,"objectToString");function bt(e){let t={};return e.forEach(function(i,u){t[i]=!0}),t}n(bt,"arrayToHash");function Et(e,t,i,u,s){let g=[];for(let o=0,a=t.length;o<a;++o)re(t,String(o))?g.push(z(e,t,i,u,String(o),!0)):g.push("");return s.forEach(function(o){o.match(/^\d+$/)||g.push(z(e,t,i,u,o,!0))}),g}n(Et,"formatArray");function B(e){return"["+Error.prototype.toString.call(e)+"]"}n(B,"formatError");function P(e,t,i){if(e.customInspect&&t&&N(t.inspect)&&t.inspect!==b&&!(t.constructor&&t.constructor.prototype===t)){let d=t.inspect(i,e);return te(d)||(d=P(e,d,i)),d}let u=yt(e,t);if(u)return u;let s=Object.keys(t),g=bt(s);try{e.showHidden&&Object.getOwnPropertyNames&&(s=Object.getOwnPropertyNames(t))}catch{}if(M(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return B(t);if(s.length===0){if(N(t)){let d=t.name?": "+t.name:"";return e.stylize("[Function"+d+"]","special")}if(v(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Q(t))return e.stylize(Date.prototype.toString.call(t),"date");if(M(t))return B(t)}let o="",a=!1,f=["{","}"];if(Array.isArray(t)&&(a=!0,f=["[","]"]),N(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),v(t)&&(o=" "+RegExp.prototype.toString.call(t)),Q(t)&&(o=" "+Date.prototype.toUTCString.call(t)),M(t)&&(o=" "+B(t)),s.length===0&&(!a||t.length==0))return f[0]+o+f[1];if(i<0)return v(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let h;return a?h=Et(e,t,i,g,s):h=s.map(function(d){return z(e,t,i,g,d,a)}),e.seen.pop(),Ot(h,o,f)}n(P,"formatValue");function z(e,t,i,u,s,g){let o,a,f;f={value:void 0};try{f.value=t[s]}catch{}try{Object.getOwnPropertyDescriptor&&(f=Object.getOwnPropertyDescriptor(t,s)||f)}catch{}if(f.get?f.set?a=e.stylize("[Getter/Setter]","special"):a=e.stylize("[Getter]","special"):f.set&&(a=e.stylize("[Setter]","special")),re(u,s)||(o="["+s+"]"),a||(e.seen.indexOf(f.value)<0?(ne(i)?a=P(e,f.value,null):a=P(e,f.value,i-1),a.indexOf(`
|
|
27
27
|
`)>-1&&(g?a=a.split(`
|
|
28
28
|
`).map(function(h){return" "+h}).join(`
|
|
29
29
|
`).substr(2):a=`
|
|
30
30
|
`+a.split(`
|
|
31
31
|
`).map(function(h){return" "+h}).join(`
|
|
32
|
-
`))):a=e.stylize("[Circular]","special")),ee(o)){if(g&&s.match(/^\d+$/))return a;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+": "+a}n(z,"formatProperty");function yt(e,t){if(ee(t))return e.stylize("undefined","undefined");if(te(t)){let i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(
|
|
32
|
+
`))):a=e.stylize("[Circular]","special")),ee(o)){if(g&&s.match(/^\d+$/))return a;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+": "+a}n(z,"formatProperty");function yt(e,t){if(ee(t))return e.stylize("undefined","undefined");if(te(t)){let i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(_t(t))return e.stylize(""+t,"number");if(pt(t))return e.stylize(""+t,"boolean");if(ne(t))return e.stylize("null","null")}n(yt,"formatPrimitive");function Ot(e,t,i){let u=0;return e.reduce(function(g,o){return u++,o.indexOf(`
|
|
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
|
-
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}n(Ot,"reduceToSingleString")});var oe=R(
|
|
35
|
+
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}n(Ot,"reduceToSingleString")});var oe=R(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.format=void 0;var Rt=K(),Lt=ie(),Tt=n((e,...t)=>(0,Rt.format)(Lt.inspect,e,t),"format");w.format=Tt});var ue=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var Pt=X(),Ct=oe(),S=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,Pt.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 s=Date.now()-(this.last||Date.now());i=(0,Ct.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${s}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=S;var I=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function se(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(se,"extract");var L;function wt(e){e||(e=[]),typeof e=="string"&&(e=se(e)),L=new I(e)}n(wt,"withoutEnv");m.withoutEnv=wt;function St(e){let t=globalThis.DEBUG;L||(L=new I(se(t)));let i=new S(L,e);return L.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}n(St,"debug");m.debug=St});var Mt={};ye(Mt,{PdpService:()=>H});module.exports=Re(Mt);var ge=Oe(ue());var E=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};var k="2024-03-14",ce=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 le(){return new _({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:k,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ce[k]},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(le,"getMockEnvironment");var _=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=le()),this.#e}constructor({build:t,runtime:i}){let u;try{if(i.__ZUPLO_CONFIG){let s=atob(i.__ZUPLO_CONFIG);u=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=u??{},this.build=t,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 managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get 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=(0,ge.debug)("zuplo:runtime:external-service");function It(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=_.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}n(It,"getServiceAuth");async function fe(e,t){let i=It();if(i)if(y(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),s=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 a;if(i.customServiceMapping&&i.customServiceMapping[s])a=`https://${i.customServiceMapping[s]}`;else if(_.instance.useLegacyServiceRouting)a=`https://${s}.zuptunnel.com`;else{y("Using sha256 service routing");let d=_.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)a=`https://${await Ut(s,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw y("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}let f=new URL(`${a}${u.pathname}${u.search}`);y(`Calling external service: ${f.toString()}`);let h=await U.fetch(f.toString(),g);if(h.status===403&&h.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:a}),new E("Could not connect to secure tunnel.");return h}else throw y("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw y("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}n(fe,"externalServiceHandler");async function Ut(e,t,i,u){let s=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),a=At(u);y(`Hashing service name: ${g}-${s}.${g}-${o}-${a}`);let f=await ae(`${g}-${s}`),h=await ae(`${g}-${o}-${a}`);return`${f}.${h}`}n(Ut,"hashServiceName");async function ae(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)}n(ae,"hashSegment");function At(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(At,"sanitizeEnvironmentType");var he=new Map;he.set("service:",fe);var de=globalThis.fetch;function D(e,t){let i=Nt(t);if(typeof e=="string"){let u=new URL(e),s=he.get(u.protocol);return s?s(e,i):de(e,i)}else return de(e,i)}n(D,"internalFetch");globalThis.fetch=D;var Nt=n(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 vt={fetch:D},U=vt;var H=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 i=await U.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()}};
|
|
36
36
|
/*! For license information please see exports.js.LEGAL.txt */
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as e}from"./chunk-4DUPDUSC.js";var
|
|
26
|
-
/*! For license information please see chunk-
|
|
25
|
+
import{a as e}from"./chunk-4DUPDUSC.js";var r="2024-03-14",u=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 _(){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:r,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:u[r]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}e(_,"getMockEnvironment");var t=class l{static{e(this,"Environment")}config;static#e;static#t=!1;static initialize(n){this.#e||(this.#e=new l(n),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=_()),this.#e}constructor({build:n,runtime:i}){let o;try{if(i.__ZUPLO_CONFIG){let s=atob(i.__ZUPLO_CONFIG);o=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=o??{},this.build=n,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 managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get 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{t as a};
|
|
26
|
+
/*! For license information please see chunk-DCA73QUZ.js.LEGAL.txt */
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a}from"./chunk-
|
|
26
|
-
/*! For license information please see chunk-
|
|
25
|
+
import{a}from"./chunk-DCA73QUZ.js";import{a as n}from"./chunk-4DUPDUSC.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>="0".charCodeAt(0)&&i<="9".charCodeAt(0)||i>="A".charCodeAt(0)&&i<="Z".charCodeAt(0)||i>="a".charCodeAt(0)&&i<="z".charCodeAt(0)?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-DV6LG6L2.js.LEGAL.txt */
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as E}from"./chunk-
|
|
25
|
+
import{a as E}from"./chunk-DCA73QUZ.js";import{a as r,b as R,c as he}from"./chunk-4DUPDUSC.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-KKIQMPVP.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-
|
|
36
|
+
/*! For license information please see chunk-TC3FNLPZ.js.LEGAL.txt */
|
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as qe,d as Re,e as Ia,f as qn,g as Zn,h as Ea,i as xa}from"./chunk-FYAUORKR.js";import{a as Ge,b as W,c as _,d as m,e as ni,f as F,g as ri}from"./chunk-ZRDXIUWC.js";import{a as f}from"./chunk-KKIQMPVP.js";import{a as s,c as Ve}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Gt=globalThis,oi=Gt.caches;if(oi){let n=oi.open;Gt.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Gt.caches.default,Object.freeze(Gt.caches)}var ii=new Map,Fn=class{static{s(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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}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)})}},rt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ii.get(e);r||(r=new Fn(t),ii.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 $n="__zuplo-expiry-header",xt=class{static{s(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 i=o.headers.get($n);if(!i){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(i);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($n,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.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($n,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ie=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new rt(r),this.#n=new xt(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var si="zuplo-request-id",We="zp-rid",jn="zp-body-removed",Ke="cf-ray",ai="x-real-ip",zn="cf-ipcity",Bn="cf-ipcontinent",Vn="cf-ipcountry",Gn="cf-iplongitude",Wn="cf-iplatitude",ui="cf-region",ci="cf-region-code",li="cf-metro-code",di="cf-postal-code",pi="cf-timezone",mi="zp-ipcity",gi="zp-ipcontinent",fi="zp-ipcountry",hi="zp-iplongitude",yi="zp-iplatitude",bi="true-client-ip",Kn="zp-asn",Jn="zp-asorg",Xn="zp-colo",Yn="zp-postalcode",Qn="zp-metrocode",er="zp-region",tr="zp-regioncode",nr="zp-timezone",wi=[zn,Bn,Vn,Gn,Wn,Kn,Jn,Xn,Yn,Qn,er,tr,nr],Ri=["zp-","cf-"],Pi=[We,Ke,jn];var Tt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var us=Ve(Ge());import{trace as uu}from"@opentelemetry/api";import{SpanStatusCode as Ta,trace as va}from"@opentelemetry/api";import{SpanStatusCode as sr,trace as ar}from"@opentelemetry/api";var Ii=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ei(n){Ii=n}s(Ei,"setTelemetryInitFunction");var xi=s(n=>Ii(n),"proxyHandler");var Ze=class{static{s(this,"RuntimePlugin")}},Me=class extends Ze{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Jt=class extends Me{static{s(this,"MeteringPlugin")}},vt=class extends Ze{static{s(this,"TelemetryPlugin")}};var Xt=new Set,Ti=new Set;function g(n){Ti.has(n)||(Ti.add(n),Xt.add(n))}s(g,"trackFeature");function vi(){let n=[...Xt];return Xt.clear(),n}s(vi,"getUnsentFeatures");function Si(n){for(let e of n)Xt.add(e)}s(Si,"restoreFeatures");var St=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new _("Error in custom 'problemResponseFormat'",{cause:i})}})}},Je=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await St.problemResponseFormat(e,t,r)}};function Yt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Yt(t)}return Object.freeze(n)}s(Yt,"deepFreeze");var te=class n extends Request{static{s(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 Yt(this.#e)}get params(){return Yt(this.#t)}user};var Ct={},He=[],rr=[],or=[],ir=[];var Qt={addPlugin(n){He.push(n)},addRequestHook(n){rr.push(n)},addResponseSendingHook(n){or.push(n)},addResponseSendingFinalHook(n){ir.push(n)}},Oi=s(async(n,e)=>{if(rr.length===0)return n;let t=ar.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of rr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:sr.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ai=s(async(n,e,t)=>{if(or.length===0)return n;let r=ar.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of or)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:sr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Li=s(async(n,e,t)=>{if(ir.length===0)return;let r=ar.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of ir)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:sr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ci=!1;async function ki(n){if(!Ci){n&&(g("runtime.extensions"),await n(Qt)),Ct.value=Qt;for(let e of He)if(e instanceof vt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});Ei(t)}for(let e of He)e instanceof Me&&await e.initialize(Qt);St.setProblemResponseFormat(Qt.problemResponseFormat),Ci=!0}}s(ki,"initializeRuntime");var ur={Json:"application/json",Form:"application/x-www-form-urlencoded"};function cr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ur.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ur.Json)||!e?JSON.stringify(n):n}s(cr,"serialize");function ot(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(ot,"isSystemRoute");var de=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>va.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:Ta.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let S=a.pop();return S?S(o,i,t,u):await this.#e(async j=>{let q=await r(j,i);return Sa(q)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ot(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ot(o,l);i.dispatchEvent(p);let h=ye.getContextExtensions(i),y=h.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{O=await h.onResponseSending(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{O=await Ai(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new At(o,O));try{await h.onResponseSendingFinal(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Li(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function Sa(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(cr(n),{headers:{"content-type":"application/json"}})}s(Sa,"resultToResponse");var en=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(en||{}),_i={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 Ca={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"},lr=Ca;function Oa(n){return`${new URL(n.url).pathname}`}s(Oa,"instance");function Aa(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(Ke);return r&&(t.rayId=r),t}s(Aa,"trace");var La=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Oa(e),trace:Aa(e,t),...r},additionalHeaders:o,statusText:lr[n.status]}),"merge"),dr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:_i[e],...t}}},x=class extends dr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=La(this.getProblemFromStatus(e),t,r,o,i);return Je.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Fe=class extends Ze{static{s(this,"MetricsPlugin")}};var X=class n{static{s(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 W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var tn=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=f.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,X.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=vi(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,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":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();X.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Si(u)}}};var se=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Lt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Lt={name:"__system-no-version",pathPrefix:""};var be=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Ke)??void 0,c=n.headers.get(bi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof se&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,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:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new tn(e)),He.forEach(O=>{if(O instanceof Fe){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(h,e)}),a},"metricsProcessor");var pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=f.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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&X.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new de({processors:[be],handler:t,gateway:e}),o=new se({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:ka}=Object.prototype,{propertyIsEnumerable:_a}=Object.prototype;function mr(n){return ka.call(n)}s(mr,"toString");function Ee(n){return typeof n=="string"}s(Ee,"isString");function it(n){return Ee(n)&&n!==""}s(it,"isNonEmptyString");function Ni(n){return mr(n)==="[object RegExp]"}s(Ni,"isRegexp");function Di(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>_a.call(n,e))]}s(Di,"getOwnEnumerableKeys");function Xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Xe,"isObject");function gr(n){return typeof n=="number"&&!isNaN(n)}s(gr,"isNumber");function fr(n){return n===!0||n===!1}s(fr,"isBoolean");function Mi(n){return typeof n>"u"}s(Mi,"isUndefined");function Hi(n){return Mi(n)||n===null}s(Hi,"isUndefinedOrNull");function kt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(kt,"isErrorLike");var Ui=new Map;function st(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=Ui.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ui.set(n,r),r}s(st,"statusCodesStringToNumberArray");function Ye(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new _(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ye,"getValueFromRequestUser");function Qe(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Qe,"parseValueToStringArray");function qi(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Xe(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!it(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!gr(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!fr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=hr(t,"allowedHeaders"),o=hr(t,"allowedMethods"),i=hr(t,"exposeHeaders"),a;try{a=Qe(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(qi,"parseCorsPolicies");function hr(n,e){let t;if(n[e]!==void 0)try{t=Qe(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(hr,"parseOptionalProperty");var nn=s((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"),rn=s((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 yr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,O=Na(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),o=new de({processors:[be],handler:r,gateway:e}),i=new se({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Na=s((n,e,t,r,o)=>{let i={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{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=nn(a.allowedOrigins,t);return u?{isValid:!0,headers:rn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Zi=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new de({processors:[be],handler:t,gateway:e}),o=new se({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 br=new se({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Fi=s((n,e)=>{let t=s(async(o,i)=>{let a=Ct.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new de({processors:[be],handler:t,gateway:e});n.addRoute(br,r.execute)},"registerNotMatchedHandler");var Da=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],$i=s(n=>{Da.forEach(e=>n.delete(e))},"stripCorsHeaders"),on=s(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 $i(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ma(o,t.routeData.corsPolicies),u=Ha(n,a),c=new Headers(i.headers);return $i(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ma=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ha=s((n,e)=>{let t=nn(e.allowedOrigins,n.headers.get("origin"));return t?rn(e,t):{}},"getCorsHeaders");var wr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new de({processors:[on],handler:t,gateway:e}),o=new se({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ji,trace as zi}from"@opentelemetry/api";var ke={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 sn=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},pe=class extends sn{static{s(this,"InboundPolicy")}},$e=class extends sn{static{s(this,"OutboundPolicy")}};var Ir=class extends pe{static{s(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)}},Er=class extends $e{static{s(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)}},Rr=new Map;function _t(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Rr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ir(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Rr.set(a.name,c)}),t.map(i=>{let a=Rr.get(i);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}s(_t,"getInboundPolicyInstances");var Pr=new Map;function Ua(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Pr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof $e)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Er(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Pr.set(i.name,u)}),t.map(o=>{let i=Pr.get(o);if(i===void 0)throw new _("Internal error. Policy not found in cache.");return i})}s(Ua,"getOutboundPolicyInstances");var xr=s(n=>async(e,t)=>{let r=ye.getContextExtensions(t),o=zi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:ji.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),qa=s(n=>async(e,t,r)=>{let o=zi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{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(ke.PolicyName,c.policyName),d.setAttribute(ke.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:ji.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),an=s(async(n,e,t,r)=>{let o=_t(e.route,t.routeData.policies),i=Ua(e.route,t.routeData.policies);return Vi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Bi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Vi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Bi,"createInternalPolicyProcessor");async function Vi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=xr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=qa(r),d;return f.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)}}s(Vi,"executePolicyProcessor");function Gi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Za,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,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]=Fa(l,o)}i=u+1}return t}s(Gi,"parse");function Za(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Za,"decode");function Fa(n,e){try{return e(n)}catch{return n}}s(Fa,"tryDecode");function Wi(n,e){try{let t=/v\d+(-\d+)?/g,o=Gi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Wi,"devPortalBaseURL");var Ki="/__zuplo/dev-portal",$a="dev-portal-id",ja="dev-portal-host",za="zp-account",Ba="zp-project",Va="dev-portal-build",Ga=`
|
|
25
|
+
import{a as qe,d as Re,e as Ia,f as qn,g as Zn,h as Ea,i as xa}from"./chunk-DV6LG6L2.js";import{a as Ge,b as W,c as _,d as m,e as ni,f as F,g as ri}from"./chunk-TC3FNLPZ.js";import{a as f}from"./chunk-DCA73QUZ.js";import{a as s,c as Ve}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Gt=globalThis,oi=Gt.caches;if(oi){let n=oi.open;Gt.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Gt.caches.default,Object.freeze(Gt.caches)}var ii=new Map,Fn=class{static{s(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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}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)})}},rt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ii.get(e);r||(r=new Fn(t),ii.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 $n="__zuplo-expiry-header",xt=class{static{s(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 i=o.headers.get($n);if(!i){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(i);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($n,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.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($n,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ie=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new rt(r),this.#n=new xt(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},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var si="zuplo-request-id",We="zp-rid",jn="zp-body-removed",Ke="cf-ray",ai="x-real-ip",zn="cf-ipcity",Bn="cf-ipcontinent",Vn="cf-ipcountry",Gn="cf-iplongitude",Wn="cf-iplatitude",ui="cf-region",ci="cf-region-code",li="cf-metro-code",di="cf-postal-code",pi="cf-timezone",mi="zp-ipcity",gi="zp-ipcontinent",fi="zp-ipcountry",hi="zp-iplongitude",yi="zp-iplatitude",bi="true-client-ip",Kn="zp-asn",Jn="zp-asorg",Xn="zp-colo",Yn="zp-postalcode",Qn="zp-metrocode",er="zp-region",tr="zp-regioncode",nr="zp-timezone",wi=[zn,Bn,Vn,Gn,Wn,Kn,Jn,Xn,Yn,Qn,er,tr,nr],Ri=["zp-","cf-"],Pi=[We,Ke,jn];var Tt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var us=Ve(Ge());import{trace as uu}from"@opentelemetry/api";import{SpanStatusCode as Ta,trace as va}from"@opentelemetry/api";import{SpanStatusCode as sr,trace as ar}from"@opentelemetry/api";var Ii=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ei(n){Ii=n}s(Ei,"setTelemetryInitFunction");var xi=s(n=>Ii(n),"proxyHandler");var Ze=class{static{s(this,"RuntimePlugin")}},Me=class extends Ze{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Jt=class extends Me{static{s(this,"MeteringPlugin")}},vt=class extends Ze{static{s(this,"TelemetryPlugin")}};var Xt=new Set,Ti=new Set;function g(n){Ti.has(n)||(Ti.add(n),Xt.add(n))}s(g,"trackFeature");function vi(){let n=[...Xt];return Xt.clear(),n}s(vi,"getUnsentFeatures");function Si(n){for(let e of n)Xt.add(e)}s(Si,"restoreFeatures");var St=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new _("Error in custom 'problemResponseFormat'",{cause:i})}})}},Je=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await St.problemResponseFormat(e,t,r)}};function Yt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Yt(t)}return Object.freeze(n)}s(Yt,"deepFreeze");var te=class n extends Request{static{s(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 Yt(this.#e)}get params(){return Yt(this.#t)}user};var Ct={},He=[],rr=[],or=[],ir=[];var Qt={addPlugin(n){He.push(n)},addRequestHook(n){rr.push(n)},addResponseSendingHook(n){or.push(n)},addResponseSendingFinalHook(n){ir.push(n)}},Oi=s(async(n,e)=>{if(rr.length===0)return n;let t=ar.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of rr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:sr.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ai=s(async(n,e,t)=>{if(or.length===0)return n;let r=ar.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of or)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:sr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Li=s(async(n,e,t)=>{if(ir.length===0)return;let r=ar.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of ir)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:sr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ci=!1;async function ki(n){if(!Ci){n&&(g("runtime.extensions"),await n(Qt)),Ct.value=Qt;for(let e of He)if(e instanceof vt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});Ei(t)}for(let e of He)e instanceof Me&&await e.initialize(Qt);St.setProblemResponseFormat(Qt.problemResponseFormat),Ci=!0}}s(ki,"initializeRuntime");var ur={Json:"application/json",Form:"application/x-www-form-urlencoded"};function cr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ur.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ur.Json)||!e?JSON.stringify(n):n}s(cr,"serialize");function ot(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(ot,"isSystemRoute");var de=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>va.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:Ta.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let S=a.pop();return S?S(o,i,t,u):await this.#e(async j=>{let q=await r(j,i);return Sa(q)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ot(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ot(o,l);i.dispatchEvent(p);let h=ye.getContextExtensions(i),y=h.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{O=await h.onResponseSending(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{O=await Ai(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new At(o,O));try{await h.onResponseSendingFinal(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Li(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function Sa(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(cr(n),{headers:{"content-type":"application/json"}})}s(Sa,"resultToResponse");var en=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(en||{}),_i={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 Ca={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"},lr=Ca;function Oa(n){return`${new URL(n.url).pathname}`}s(Oa,"instance");function Aa(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(Ke);return r&&(t.rayId=r),t}s(Aa,"trace");var La=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Oa(e),trace:Aa(e,t),...r},additionalHeaders:o,statusText:lr[n.status]}),"merge"),dr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:_i[e],...t}}},x=class extends dr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=La(this.getProblemFromStatus(e),t,r,o,i);return Je.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Fe=class extends Ze{static{s(this,"MetricsPlugin")}};var X=class n{static{s(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 W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var tn=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=f.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,X.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=vi(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,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":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();X.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Si(u)}}};var se=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Lt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Lt={name:"__system-no-version",pathPrefix:""};var be=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Ke)??void 0,c=n.headers.get(bi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof se&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,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:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new tn(e)),He.forEach(O=>{if(O instanceof Fe){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(h,e)}),a},"metricsProcessor");var pr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=f.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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&X.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new de({processors:[be],handler:t,gateway:e}),o=new se({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:ka}=Object.prototype,{propertyIsEnumerable:_a}=Object.prototype;function mr(n){return ka.call(n)}s(mr,"toString");function Ee(n){return typeof n=="string"}s(Ee,"isString");function it(n){return Ee(n)&&n!==""}s(it,"isNonEmptyString");function Ni(n){return mr(n)==="[object RegExp]"}s(Ni,"isRegexp");function Di(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>_a.call(n,e))]}s(Di,"getOwnEnumerableKeys");function Xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Xe,"isObject");function gr(n){return typeof n=="number"&&!isNaN(n)}s(gr,"isNumber");function fr(n){return n===!0||n===!1}s(fr,"isBoolean");function Mi(n){return typeof n>"u"}s(Mi,"isUndefined");function Hi(n){return Mi(n)||n===null}s(Hi,"isUndefinedOrNull");function kt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(kt,"isErrorLike");var Ui=new Map;function st(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=Ui.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ui.set(n,r),r}s(st,"statusCodesStringToNumberArray");function Ye(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new _(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ye,"getValueFromRequestUser");function Qe(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Qe,"parseValueToStringArray");function qi(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Xe(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!it(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!gr(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!fr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=hr(t,"allowedHeaders"),o=hr(t,"allowedMethods"),i=hr(t,"exposeHeaders"),a;try{a=Qe(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(qi,"parseCorsPolicies");function hr(n,e){let t;if(n[e]!==void 0)try{t=Qe(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(hr,"parseOptionalProperty");var nn=s((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"),rn=s((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 yr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,O=Na(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),o=new de({processors:[be],handler:r,gateway:e}),i=new se({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Na=s((n,e,t,r,o)=>{let i={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{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=nn(a.allowedOrigins,t);return u?{isValid:!0,headers:rn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Zi=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new de({processors:[be],handler:t,gateway:e}),o=new se({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 br=new se({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Fi=s((n,e)=>{let t=s(async(o,i)=>{let a=Ct.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new de({processors:[be],handler:t,gateway:e});n.addRoute(br,r.execute)},"registerNotMatchedHandler");var Da=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],$i=s(n=>{Da.forEach(e=>n.delete(e))},"stripCorsHeaders"),on=s(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 $i(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ma(o,t.routeData.corsPolicies),u=Ha(n,a),c=new Headers(i.headers);return $i(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ma=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ha=s((n,e)=>{let t=nn(e.allowedOrigins,n.headers.get("origin"));return t?rn(e,t):{}},"getCorsHeaders");var wr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new de({processors:[on],handler:t,gateway:e}),o=new se({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ji,trace as zi}from"@opentelemetry/api";var ke={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 sn=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},pe=class extends sn{static{s(this,"InboundPolicy")}},$e=class extends sn{static{s(this,"OutboundPolicy")}};var Ir=class extends pe{static{s(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)}},Er=class extends $e{static{s(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)}},Rr=new Map;function _t(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Rr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ir(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Rr.set(a.name,c)}),t.map(i=>{let a=Rr.get(i);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}s(_t,"getInboundPolicyInstances");var Pr=new Map;function Ua(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Pr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof $e)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Er(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Pr.set(i.name,u)}),t.map(o=>{let i=Pr.get(o);if(i===void 0)throw new _("Internal error. Policy not found in cache.");return i})}s(Ua,"getOutboundPolicyInstances");var xr=s(n=>async(e,t)=>{let r=ye.getContextExtensions(t),o=zi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{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 te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:ji.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),qa=s(n=>async(e,t,r)=>{let o=zi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{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(ke.PolicyName,c.policyName),d.setAttribute(ke.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:ji.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),an=s(async(n,e,t,r)=>{let o=_t(e.route,t.routeData.policies),i=Ua(e.route,t.routeData.policies);return Vi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Bi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Vi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Bi,"createInternalPolicyProcessor");async function Vi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=xr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=qa(r),d;return f.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)}}s(Vi,"executePolicyProcessor");function Gi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Za,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,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]=Fa(l,o)}i=u+1}return t}s(Gi,"parse");function Za(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Za,"decode");function Fa(n,e){try{return e(n)}catch{return n}}s(Fa,"tryDecode");function Wi(n,e){try{let t=/v\d+(-\d+)?/g,o=Gi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Wi,"devPortalBaseURL");var Ki="/__zuplo/dev-portal",$a="dev-portal-id",ja="dev-portal-host",za="zp-account",Ba="zp-project",Va="dev-portal-build",Ga=`
|
|
26
26
|
<!DOCTYPE html>
|
|
27
27
|
<html lang="en">
|
|
28
28
|
<head>
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-
|
|
25
|
+
import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-DV6LG6L2.js";import"../chunk-DCA73QUZ.js";import"../chunk-4DUPDUSC.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
|
|
26
26
|
/*! For license information please see index.js.LEGAL.txt */
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{g as o}from"../../chunk-
|
|
25
|
+
import{g as o}from"../../chunk-TC3FNLPZ.js";import"../../chunk-DCA73QUZ.js";import"../../chunk-4DUPDUSC.js";export{o as PdpService};
|
|
26
26
|
/*! For license information please see exports.js.LEGAL.txt */
|
package/package.json
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|