@zuplo/runtime 6.2.15 → 6.2.18
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/esm/index.js +2 -2
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -32,7 +32,7 @@ import{a as f,b as $e,e as Pe,f as nu,g as Bn,h as Gn,i as ru,j as ou}from"./chu
|
|
|
32
32
|
`))):u=n.stylize("[Circular]","special")),Li(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(Qn,"formatProperty");function wu(n,e){if(Li(e))return n.stylize("undefined","undefined");if(_i(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(hu(e))return n.stylize(""+e,"number");if(gu(e))return n.stylize(""+e,"boolean");if(Ni(e))return n.stylize("null","null")}i(wu,"formatPrimitive");function Ru(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(Ru,"reduceToSingleString");var Mi=i((n,...e)=>Ai(Fe,n,e),"format");var er=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Si(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=Mi(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},tr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Pu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Pu,"extract");var nn;function he(n){let e=globalThis.DEBUG;nn||(nn=new tr(Pu(e)));let t=new er(nn,n);return nn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(he,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},rn=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Xe=he("zuplo:runtime:external-service");function Iu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=f.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Iu,"getServiceAuth");async function qi(n,e){let t=Iu();if(t)if(Xe(`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(f.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Xe("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await Eu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),h=Ui(d.ENVIRONMENT_TYPE),y=await nr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${h}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw Xe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Xe(`Calling external service: ${c.toString()}`);let l=await Z.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 A("Could not connect to secure tunnel.");return l}else throw Xe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Xe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(qi,"externalServiceHandler");async function Eu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Ui(r);Xe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await nr(`${s}-${o}`),l=await nr(`${s}-${a}-${u}`);return`${c}.${l}`}i(Eu,"hashServiceName");async function nr(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(nr,"hashSegment");function Ui(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Ui,"sanitizeEnvironmentType");var Zi=new Map;Zi.set("service:",qi);var Hi=globalThis.fetch;function rr(n,e){let t=xu(e);if(typeof n=="string"){let r=new URL(n),o=Zi.get(r.protocol);return o?o(n,t):Hi(n,t)}else return Hi(n,t)}i(rr,"internalFetch");globalThis.fetch=rr;var xu=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 Tu={fetch:rr},Z=Tu;Function.prototype.toString=function(){return"[native code]"};var on=globalThis,$i=on.caches;if($i){let n=$i.open;on.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete on.caches.default,Object.freeze(on.caches)}var Fi=new Map,or=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)})}},je=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Fi.get(e);r||(r=new or(t),Fi.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 ir="__zuplo-expiry-header",St=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(ir);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(ir,`${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(ir,`${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 oe=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new je(r),this.#n=new St(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 ji="zuplo-request-id",et="zp-rid",sr="zp-body-removed",tt="cf-ray",zi="x-real-ip",ar="cf-ipcity",ur="cf-ipcontinent",cr="cf-ipcountry",lr="cf-iplongitude",dr="cf-iplatitude",Bi="cf-region",Gi="cf-region-code",Vi="cf-metro-code",Wi="cf-postal-code",Ki="cf-timezone",Ji="zp-ipcity",Qi="zp-ipcontinent",Yi="zp-ipcountry",Xi="zp-iplongitude",es="zp-iplatitude",ts="true-client-ip",pr="zp-asn",mr="zp-asorg",gr="zp-colo",fr="zp-postalcode",hr="zp-metrocode",yr="zp-region",br="zp-regioncode",wr="zp-timezone",ns=[ar,ur,cr,lr,dr,pr,mr,gr,fr,hr,yr,br,wr],rs=["zp-","cf-"],os=[et,tt,sr];var At=Symbol("zuplo_meters"),kt=Symbol("zuplo_dynamic_meters"),sn="system-logger";var re=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as ac}from"@opentelemetry/api";import{SpanStatusCode as vu,trace as Cu}from"@opentelemetry/api";import{SpanStatusCode as Er,trace as xr}from"@opentelemetry/api";var is=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ss(n){is=n}i(ss,"setTelemetryInitFunction");var as=i(n=>is(n),"proxyHandler");var ze=class{static{i(this,"RuntimePlugin")}},qe=class extends ze{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},an=class extends qe{static{i(this,"MeteringPlugin")}},Lt=class extends ze{static{i(this,"TelemetryPlugin")}};var un=new Set,us=new Set;function g(n){us.has(n)||(us.add(n),un.add(n))}i(g,"trackFeature");function cs(){let n=[...un];return un.clear(),n}i(cs,"getUnsentFeatures");function ls(n){for(let e of n)un.add(e)}i(ls,"restoreFeatures");var _t=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},nt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await _t.problemResponseFormat(e,t,r)}};function cn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&cn(t)}return Object.freeze(n)}i(cn,"deepFreeze");var te=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 cn(this.#e)}get params(){return cn(this.#t)}user};var Nt={},Ue=[],Rr=[],Pr=[],Ir=[];var ln={addPlugin(n){Ue.push(n)},addRequestHook(n){Rr.push(n)},addResponseSendingHook(n){Pr.push(n)},addResponseSendingFinalHook(n){Ir.push(n)}},ps=i(async(n,e)=>{if(Rr.length===0)return n;let t=xr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Rr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(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:Er.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ms=i(async(n,e,t)=>{if(Pr.length===0)return n;let r=xr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Pr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Er.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),gs=i(async(n,e,t)=>{if(Ir.length===0)return;let r=xr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Ir)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Er.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ds=!1;async function fs(n){if(!ds){n&&(g("runtime.extensions"),await n(ln)),Nt.value=ln;for(let e of Ue)if(e instanceof Lt){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});ss(t)}for(let e of Ue)e instanceof qe&&await e.initialize(ln);_t.setProblemResponseFormat(ln.problemResponseFormat),ds=!0}}i(fs,"initializeRuntime");var Tr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function vr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Tr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Tr.Json)||!e?JSON.stringify(n):n}i(vr,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>Cu.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:vu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async R=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async $=>{let U=await r($,s);return Ou(U)},t)(R,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(dt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Dt(o,l);s.dispatchEvent(p);let h=be.getContextExtensions(s),y=h.latestRequest,S;try{S=await p.mutableResponse}catch(R){return s.log.error(R),t.errorHandler(o,s,R)}try{S=await h.onResponseSending(S,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}try{S=await ms(S,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}s.dispatchEvent(new Mt(o,S));try{await h.onResponseSendingFinal(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await gs(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return S},"#toZuploPipeline")};function Ou(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(vr(n),{headers:{"content-type":"application/json"}})}i(Ou,"resultToResponse");var dn=(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))(dn||{}),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 Su={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"},Cr=Su;function Au(n){return`${new URL(n.url).pathname}`}i(Au,"instance");function ku(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(tt);return r&&(t.rayId=r),t}i(ku,"trace");var Lu=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Au(e),trace:ku(e,t),...r},additionalHeaders:o,statusText:Cr[n.status]}),"merge"),Or=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?nt.format(e,t,r):nt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:hs[e],...t}}},E=class extends Or{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Lu(this.getProblemFromStatus(e),t,r,o,s);return nt.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var Be=class extends ze{static{i(this,"MetricsPlugin")}};var Q=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 K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var pn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=f.instance.loggingId,this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=cs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await Z.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();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ls(u)}},"dispatchFunction")};var le=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=qt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},qt={name:"__system-no-version",pathPrefix:""};var we=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(tt)??void 0,c=n.headers.get(ts)??void 0,l=e.incomingRequestProperties,d;e.route instanceof le&&(d=e.route.systemRouteName);let p=be.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:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new pn(e)),Ue.forEach(S=>{if(S instanceof Be){let R=S.getTransport();y.push(R)}}),y.forEach(S=>{S.pushMetrics(h,e)}),a},"metricsProcessor");var Sr=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 E.notFound(s,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.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new le({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:_u}=Object.prototype,{propertyIsEnumerable:Nu}=Object.prototype;function Ar(n){return _u.call(n)}i(Ar,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function pt(n){return xe(n)&&n!==""}i(pt,"isNonEmptyString");function ys(n){return Ar(n)==="[object RegExp]"}i(ys,"isRegexp");function bs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Nu.call(n,e))]}i(bs,"getOwnEnumerableKeys");function rt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(rt,"isObject");function kr(n){return typeof n=="number"&&!isNaN(n)}i(kr,"isNumber");function Lr(n){return n===!0||n===!1}i(Lr,"isBoolean");function ws(n){return typeof n>"u"}i(ws,"isUndefined");function Rs(n){return ws(n)||n===null}i(Rs,"isUndefinedOrNull");function Ut(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Ut,"isErrorLike");var Ps=new Map;function Ge(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=Ps.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 Ps.set(n,r),r}i(Ge,"statusCodesStringToNumberArray");function He(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(He,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function Is(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(!rt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!kr(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&&!Lr(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=_r(t,"allowedHeaders"),o=_r(t,"allowedMethods"),s=_r(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Is,"parseCorsPolicies");function _r(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(_r,"parseOptionalProperty");var mn=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"),gn=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 Nr=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 E.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return E.notFound(a,u);let y=h.routeConfiguration,S=Du(l,d,p,y,t);return S.isValid?new Response(void 0,{status:200,statusText:"OK",headers:S.headers}):(S.error&&u.log.warn(S.error),E.notFound(a,u))},"optionsHandler"),o=new me({processors:[we],handler:r,gateway:e}),s=new le({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Du=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=mn(a.allowedOrigins,t);return u?{isValid:!0,headers:gn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Es=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 me({processors:[we],handler:t,gateway:e}),o=new le({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 Dr=new le({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),xs=i((n,e)=>{let t=i(async(o,s)=>{let a=Nt.value?.notFoundHandler;if(a){let u=be.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return E.notFound(o,s)},"notFoundHandler"),r=new me({processors:[we],handler:t,gateway:e});n.addRoute(Dr,r.execute)},"registerNotMatchedHandler");var Mu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ts=i(n=>{Mu.forEach(e=>n.delete(e))},"stripCorsHeaders"),fn=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 Ts(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 K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=qu(o,t.routeData.corsPolicies),u=Uu(n,a),c=new Headers(s.headers);return Ts(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"),qu=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Uu=i((n,e)=>{let t=mn(e.allowedOrigins,n.headers.get("origin"));return t?gn(e,t):{}},"getCorsHeaders");var Mr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new me({processors:[fn],handler:t,gateway:e}),o=new le({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as vs,trace as Cs}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var hn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new A(`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}},ae=class extends hn{static{i(this,"InboundPolicy")}},Ve=class extends hn{static{i(this,"OutboundPolicy")}};var Hr=class extends ae{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)}},Zr=class extends Ve{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)}},qr=new Map;function Ht(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!qr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Hr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);qr.set(a.name,c)}),t.map(s=>{let a=qr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Ht,"getInboundPolicyInstances");var Ur=new Map;function Zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!Ur.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ve)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Zr(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);Ur.set(a.name,c)}),t.map(s=>{let a=Ur.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Zt,"getOutboundPolicyInstances");var $r=i(n=>async(e,t)=>{let r=be.getContextExtensions(t),o=Cs.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 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:vs.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{s.end()}})},"toStackedInboundHandler"),Fr=i(n=>async(e,t,r)=>{let o=Cs.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:vs.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),yn=i(async(n,e,t,r)=>{let o=Ht(e.route,t.routeData.policies),s=Zt(e.route,t.routeData.policies);return Ss({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Os({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ss({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Os,"createInternalPolicyProcessor");async function Ss({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=$r(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Fr(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)}}i(Ss,"executePolicyProcessor");function As(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Hu,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]=Zu(l,o)}s=u+1}return t}i(As,"parse");function Hu(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Hu,"decode");function Zu(n,e){try{return e(n)}catch{return n}}i(Zu,"tryDecode");function ks(n,e){try{let t=/v\d+(-\d+)?/g,o=As(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ks,"devPortalBaseURL");var Ls="/__zuplo/dev-portal",$u="dev-portal-id",Fu="dev-portal-host",ju="zp-account",zu="zp-project",Bu="dev-portal-build",Gu=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Ru,"reduceToSingleString");var Mi=i((n,...e)=>Ai(Fe,n,e),"format");var er=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Si(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=Mi(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},tr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Pu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Pu,"extract");var nn;function he(n){let e=globalThis.DEBUG;nn||(nn=new tr(Pu(e)));let t=new er(nn,n);return nn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(he,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},rn=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Xe=he("zuplo:runtime:external-service");function Iu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=f.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Iu,"getServiceAuth");async function qi(n,e){let t=Iu();if(t)if(Xe(`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(f.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Xe("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await Eu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),h=Ui(d.ENVIRONMENT_TYPE),y=await nr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${h}`);y==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||y==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw Xe("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Xe(`Calling external service: ${c.toString()}`);let l=await Z.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 A("Could not connect to secure tunnel.");return l}else throw Xe("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Xe("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(qi,"externalServiceHandler");async function Eu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Ui(r);Xe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await nr(`${s}-${o}`),l=await nr(`${s}-${a}-${u}`);return`${c}.${l}`}i(Eu,"hashServiceName");async function nr(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(nr,"hashSegment");function Ui(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Ui,"sanitizeEnvironmentType");var Zi=new Map;Zi.set("service:",qi);var Hi=globalThis.fetch;function rr(n,e){let t=xu(e);if(typeof n=="string"){let r=new URL(n),o=Zi.get(r.protocol);return o?o(n,t):Hi(n,t)}else return Hi(n,t)}i(rr,"internalFetch");globalThis.fetch=rr;var xu=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 Tu={fetch:rr},Z=Tu;Function.prototype.toString=function(){return"[native code]"};var on=globalThis,$i=on.caches;if($i){let n=$i.open;on.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete on.caches.default,Object.freeze(on.caches)}var Fi=new Map,or=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)})}},je=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Fi.get(e);r||(r=new or(t),Fi.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 ir="__zuplo-expiry-header",St=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(ir);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(ir,`${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(ir,`${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 oe=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new je(r),this.#n=new St(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 ji="zuplo-request-id",et="zp-rid",sr="zp-body-removed",tt="cf-ray",zi="x-real-ip",ar="cf-ipcity",ur="cf-ipcontinent",cr="cf-ipcountry",lr="cf-iplongitude",dr="cf-iplatitude",Bi="cf-region",Gi="cf-region-code",Vi="cf-metro-code",Wi="cf-postal-code",Ki="cf-timezone",Ji="zp-ipcity",Qi="zp-ipcontinent",Yi="zp-ipcountry",Xi="zp-iplongitude",es="zp-iplatitude",ts="true-client-ip",pr="zp-asn",mr="zp-asorg",gr="zp-colo",fr="zp-postalcode",hr="zp-metrocode",yr="zp-region",br="zp-regioncode",wr="zp-timezone",ns=[ar,ur,cr,lr,dr,pr,mr,gr,fr,hr,yr,br,wr],rs=["zp-","cf-"],os=[et,tt,sr];var At=Symbol("zuplo_meters"),kt=Symbol("zuplo_dynamic_meters"),sn="system-logger";var re=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as ac}from"@opentelemetry/api";import{SpanStatusCode as vu,trace as Cu}from"@opentelemetry/api";import{SpanStatusCode as Er,trace as xr}from"@opentelemetry/api";var is=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ss(n){is=n}i(ss,"setTelemetryInitFunction");var as=i(n=>is(n),"proxyHandler");var ze=class{static{i(this,"RuntimePlugin")}},qe=class extends ze{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},an=class extends qe{static{i(this,"MeteringPlugin")}},Lt=class extends ze{static{i(this,"TelemetryPlugin")}};var un=new Set,us=new Set;function g(n){us.has(n)||(us.add(n),un.add(n))}i(g,"trackFeature");function cs(){let n=[...un];return un.clear(),n}i(cs,"getUnsentFeatures");function ls(n){for(let e of n)un.add(e)}i(ls,"restoreFeatures");var _t=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},nt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await _t.problemResponseFormat(e,t,r)}};function cn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&cn(t)}return Object.freeze(n)}i(cn,"deepFreeze");var te=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 cn(this.#e)}get params(){return cn(this.#t)}user};var Nt={},Ue=[],Rr=[],Pr=[],Ir=[];var ln={addPlugin(n){Ue.push(n)},addRequestHook(n){Rr.push(n)},addResponseSendingHook(n){Pr.push(n)},addResponseSendingFinalHook(n){Ir.push(n)}},ps=i(async(n,e)=>{if(Rr.length===0)return n;let t=xr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Rr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(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:Er.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ms=i(async(n,e,t)=>{if(Pr.length===0)return n;let r=xr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Pr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Er.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),gs=i(async(n,e,t)=>{if(Ir.length===0)return;let r=xr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Ir)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Er.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ds=!1;async function fs(n){if(!ds){n&&(g("runtime.extensions"),await n(ln)),Nt.value=ln;for(let e of Ue)if(e instanceof Lt){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});ss(t)}for(let e of Ue)e instanceof qe&&await e.initialize(ln);_t.setProblemResponseFormat(ln.problemResponseFormat),ds=!0}}i(fs,"initializeRuntime");var Tr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function vr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Tr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Tr.Json)||!e?JSON.stringify(n):n}i(vr,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>Cu.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:vu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async R=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async $=>{let U=await r($,s);return Ou(U)},t)(R,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(dt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Dt(o,l);s.dispatchEvent(p);let h=be.getContextExtensions(s),y=h.latestRequest,S;try{S=await p.mutableResponse}catch(R){return s.log.error(R),t.errorHandler(o,s,R)}try{S=await h.onResponseSending(S,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}try{S=await ms(S,y,s)}catch(R){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,s,R)}s.dispatchEvent(new Mt(o,S));try{await h.onResponseSendingFinal(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await gs(l,y,s)}catch(R){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return S},"#toZuploPipeline")};function Ou(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(vr(n),{headers:{"content-type":"application/json"}})}i(Ou,"resultToResponse");var dn=(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))(dn||{}),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 Su={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"},Cr=Su;function Au(n){return`${new URL(n.url).pathname}`}i(Au,"instance");function ku(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(tt);return r&&(t.rayId=r),t}i(ku,"trace");var Lu=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Au(e),trace:ku(e,t),...r},additionalHeaders:o,statusText:Cr[n.status]}),"merge"),Or=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?nt.format(e,t,r):nt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:hs[e],...t}}},E=class extends Or{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Lu(this.getProblemFromStatus(e),t,r,o,s);return nt.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var Be=class extends ze{static{i(this,"MetricsPlugin")}};var Q=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 K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var pn=class{static{i(this,"EllieMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=cs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await Z.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();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ls(u)}},"dispatchFunction")};var le=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=qt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},qt={name:"__system-no-version",pathPrefix:""};var we=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(tt)??void 0,c=n.headers.get(ts)??void 0,l=e.incomingRequestProperties,d;e.route instanceof le&&(d=e.route.systemRouteName);let p=be.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:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new pn(e)),Ue.forEach(S=>{if(S instanceof Be){let R=S.getTransport();y.push(R)}}),y.forEach(S=>{S.pushMetrics(h,e)}),a},"metricsProcessor");var Sr=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 E.notFound(s,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.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new le({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:_u}=Object.prototype,{propertyIsEnumerable:Nu}=Object.prototype;function Ar(n){return _u.call(n)}i(Ar,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function pt(n){return xe(n)&&n!==""}i(pt,"isNonEmptyString");function ys(n){return Ar(n)==="[object RegExp]"}i(ys,"isRegexp");function bs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Nu.call(n,e))]}i(bs,"getOwnEnumerableKeys");function rt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(rt,"isObject");function kr(n){return typeof n=="number"&&!isNaN(n)}i(kr,"isNumber");function Lr(n){return n===!0||n===!1}i(Lr,"isBoolean");function ws(n){return typeof n>"u"}i(ws,"isUndefined");function Rs(n){return ws(n)||n===null}i(Rs,"isUndefinedOrNull");function Ut(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Ut,"isErrorLike");var Ps=new Map;function Ge(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=Ps.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 Ps.set(n,r),r}i(Ge,"statusCodesStringToNumberArray");function He(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(He,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function Is(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(!rt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!kr(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&&!Lr(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=_r(t,"allowedHeaders"),o=_r(t,"allowedMethods"),s=_r(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Is,"parseCorsPolicies");function _r(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(_r,"parseOptionalProperty");var mn=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"),gn=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 Nr=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 E.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return E.notFound(a,u);let y=h.routeConfiguration,S=Du(l,d,p,y,t);return S.isValid?new Response(void 0,{status:200,statusText:"OK",headers:S.headers}):(S.error&&u.log.warn(S.error),E.notFound(a,u))},"optionsHandler"),o=new me({processors:[we],handler:r,gateway:e}),s=new le({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Du=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=mn(a.allowedOrigins,t);return u?{isValid:!0,headers:gn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Es=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 me({processors:[we],handler:t,gateway:e}),o=new le({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 Dr=new le({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),xs=i((n,e)=>{let t=i(async(o,s)=>{let a=Nt.value?.notFoundHandler;if(a){let u=be.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return E.notFound(o,s)},"notFoundHandler"),r=new me({processors:[we],handler:t,gateway:e});n.addRoute(Dr,r.execute)},"registerNotMatchedHandler");var Mu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ts=i(n=>{Mu.forEach(e=>n.delete(e))},"stripCorsHeaders"),fn=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 Ts(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 K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=qu(o,t.routeData.corsPolicies),u=Uu(n,a),c=new Headers(s.headers);return Ts(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"),qu=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Uu=i((n,e)=>{let t=mn(e.allowedOrigins,n.headers.get("origin"));return t?gn(e,t):{}},"getCorsHeaders");var Mr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new me({processors:[fn],handler:t,gateway:e}),o=new le({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as vs,trace as Cs}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var hn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new A(`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}},ae=class extends hn{static{i(this,"InboundPolicy")}},Ve=class extends hn{static{i(this,"OutboundPolicy")}};var Hr=class extends ae{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)}},Zr=class extends Ve{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)}},qr=new Map;function Ht(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!qr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Hr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);qr.set(a.name,c)}),t.map(s=>{let a=qr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Ht,"getInboundPolicyInstances");var Ur=new Map;function Zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!Ur.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ve)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Zr(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);Ur.set(a.name,c)}),t.map(s=>{let a=Ur.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Zt,"getOutboundPolicyInstances");var $r=i(n=>async(e,t)=>{let r=be.getContextExtensions(t),o=Cs.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 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:vs.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{s.end()}})},"toStackedInboundHandler"),Fr=i(n=>async(e,t,r)=>{let o=Cs.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:vs.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),yn=i(async(n,e,t,r)=>{let o=Ht(e.route,t.routeData.policies),s=Zt(e.route,t.routeData.policies);return Ss({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Os({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Ss({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Os,"createInternalPolicyProcessor");async function Ss({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=$r(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Fr(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)}}i(Ss,"executePolicyProcessor");function As(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Hu,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]=Zu(l,o)}s=u+1}return t}i(As,"parse");function Hu(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Hu,"decode");function Zu(n,e){try{return e(n)}catch{return n}}i(Zu,"tryDecode");function ks(n,e){try{let t=/v\d+(-\d+)?/g,o=As(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ks,"devPortalBaseURL");var Ls="/__zuplo/dev-portal",$u="dev-portal-id",Fu="dev-portal-host",ju="zp-account",zu="zp-project",Bu="dev-portal-build",Gu=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -53,7 +53,7 @@ import{a as f,b as $e,e as Pe,f as nu,g as Bn,h as Gn,i as ru,j as ou}from"./chu
|
|
|
53
53
|
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let S=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return S.length<=u.inlineCharacterLimit?S:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
54
54
|
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ys(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((S,R)=>{let C=a.length-1===R?p.newline:","+p.newlineOrSpace,N=s(S,u,c+d,l+1);return u.transform&&(N=u.transform(a,R,N)),p.indent+N+C}).join("")+p.pad+"]";return r.pop(),h(y)}if(rt(a)){let y=bs(a);if(u.filter&&(y=y.filter(R=>u.filter?.(a,R))),y.length===0)return"{}";r.push(a);let S="{"+p.newline+y.map((R,C)=>{let N=y.length-1===C?p.newline:","+p.newlineOrSpace,k=typeof R=="symbol",$=!k&&/^[a-z$_][$\w]*$/i.test(R),U=k||$?R:s(R,u,"",l+1),F=s(a[R],u,c+d,l+1);return u.transform&&(F=u.transform(a,R,F)),p.indent+String(U)+": "+F+N}).join("")+p.pad+"}";return r.pop(),h(S)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
55
55
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(wn,"stringifyObject");function We(n){return n.map(e=>Ie(e))}i(We,"makeErrorsSerializable");function mt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Ze(Ie(e))}i(mt,"extractBestMessage");function qs(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ut(t))if(t.stack)e.push(t.stack);else{let r=wn(Ie(t));e.push(r)}else if(typeof t=="object"){let r=wn(t);e.push(r)}else{let r=Br(t);e.push(r)}}),e.join(`
|
|
56
|
-
`)}i(qs,"messagesToMultilineText");function Ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ze,"stringifyNonString");function Br(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ar(n):"unknown"}i(Br,"stringifyNonStringToText");import{importPKCS8 as ec,SignJWT as tc}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new tc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Us(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Gr("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Us,"exchangeIDTokenForGcpWorkloadToken");async function Hs({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return $s(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Hs,"generateServiceAccountIDToken");async function Zs(n,e,t){return Gr(n,{token:e,returnSecureToken:!0},t)}i(Zs,"exchangeFirebaseJwtForIdToken");async function Rn(n,e,t){return Gr(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Rn,"exchangeGgpJwtForIdToken");async function Gr(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return $s(n,r,t)}i(Gr,"fetchTokenFromBody");async function $s(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i($s,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ec(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function de(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await Fs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(de,"sendRemoteGlobalLog");async function Fs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:We(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Fs,"sendRemoteLogs");var nc=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Fs({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Pn,In=class{static{i(this,"RemoteLogTransport")}constructor(e){Pn||(Pn=new Y("remote-log-transport",1,nc(e)))}log(e,t){Pn.enqueue(e),t.waitUntil(Pn.waitUntilFlushed())}};var Vr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},rc="https://logging.googleapis.com/v2/entries:write?alt=json",Wr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:We(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(rc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await de({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await de({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var En="gcp";function xn(n){let e={allMessages:We(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Wr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(xn,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e.log(JSON.stringify(e))}};var Yr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Kr="__ddtags",Jr="__ddattr",Qr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),oc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Qr(r)):t.push(`${Qr(r)}:${Qr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Kr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Kr]!==void 0);a>-1&&(Object.assign(r,s[a][Kr]),s.splice(a,1));let u={},c=t.custom[Jr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Jr]!==void 0);l>-1&&(Object.assign(u,s[l][Jr]),s.splice(l,1));let d=We(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:oc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await de({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await de({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ic={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},js=i((n,e)=>t=>{let r={};return r.accountName=e.ACCOUNT_NAME,r.projectName=e.PROJECT_NAME,r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{logId:t.logId,timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ic[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var sc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=js(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Tn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Tn||(Tn=new Y("unified-log-transport",1,sc(e)))}async log(e,t){Tn.enqueue(e),t.waitUntil(Tn.waitUntilFlushed())}};var Xr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Xr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(sn);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Xr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(sn);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new In({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),e.enableRuntimeUserLogs&&e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Xr("Gateway.createRequestLoggers");let a=new bn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var eo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Wt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},to=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Kt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof le))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new eo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new to(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Wt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Wt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var no;function zs(n){no=n}i(zs,"setGlobalZuploEventContext");function Cn(){if(no===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return no}i(Cn,"getGlobalZuploEventContext");function Bs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);rs.includes(o.toLowerCase())&&!os.includes(r.toLowerCase())&&t.delete(r)}t.delete(zi)}else ns.forEach(r=>{t.delete(r)});return t}i(Bs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),uc=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:Is(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[yn,fn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=uc(e.versions),r=new Kt(t);if(e.routes.length===0)return Sr(r,this),Mr(r,this),Nr(r,this),Es(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ns(r,this),_s(r,this)),Sr(r,this),Mr(r,this),Nr(r,this);for(let s of Ue)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),xs(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=Ms(s.stack)),o={cause:s}}}return E.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;zs(r);let a=Bs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(et,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(sr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let S=new On(e.headers),R=new te(u,{params:y.params}),C=new Sn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:S}),N=y.routeConfiguration.raw();ac.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(C,R);if(y.routeConfiguration===Dr&&Nt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=$.map(U=>U.routeConfiguration).filter(U=>U instanceof it)}try{if(Q.addLogger(C,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let v=await ps(R,C);if(v instanceof Response)return v;{let H=be.getContextExtensions(C);R=v,H.latestRequest=R}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let $=y.executableHandler;cc($,y,u),De("Gateway.handleRequest - call user handler");let U=await $(R,C);if(De("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let F;if(U.headers.get(et)===null&&!U.webSocket){let v=new Headers(U.headers);v.set(et,o),F=new Response(U.body,{status:U.status,statusText:U.statusText,headers:v,cf:U.cf})}else F=U;return F}catch($){return De("Gateway - error executing handler",$),$ instanceof A?(l.error($),d.warn($)):d.error($),await this.#i(R,C,$)}}};function cc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cc,"checkHandler");var Gs=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ht([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),Vs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new A(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(pr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(mr)??void 0}get city(){return this.#e.get(ar)??this.#e.get(Ji)??void 0}get continent(){return this.#e.get(ur)??this.#e.get(Qi)??void 0}get country(){return this.#e.get(cr)??this.#e.get(Yi)??void 0}get latitude(){return this.#e.get(dr)??this.#e.get(es)??void 0}get longitude(){return this.#e.get(lr)??this.#e.get(Xi)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(Wi)??this.#e.get(fr)??void 0}get metroCode(){return this.#e.get(Vi)??this.#e.get(hr)??void 0}get region(){return this.#e.get(Bi)??this.#e.get(yr)??void 0}get regionCode(){return this.#e.get(Gi)??this.#e.get(br)??void 0}get timezone(){return this.#e.get(Ki)??this.#e.get(wr)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Gs(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Vs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as lc}from"node:async_hooks";var Ws={request:new lc};var dc="Error initializing gateway. Check your configuration for errors or contact support.",pc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",ro=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(et)??e.headers.get(ji)??crypto.randomUUID(),s=e.headers.get(tt),a={requestId:o,rayId:s};return Ws.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await fs(this.runtimeInit)}catch(c){this.handleError(c,pc,e)}return as(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function mc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(mc,"lexer");function io(n,e){e===void 0&&(e={});for(var t=mc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(z){if(l<t.length&&t[l].type===z)return t[l++].value},"tryConsume"),h=i(function(z){var x=p(z);if(x!==void 0)return x;var I=t[l],M=I.type,ue=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ue,", expected ").concat(z))},"mustConsume"),y=i(function(){for(var z="",x;x=p("CHAR")||p("ESCAPED_CHAR");)z+=x;return z},"consumeText"),S=i(function(z){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(z.indexOf(M)>-1)return!0}return!1},"isSafe"),R=i(function(z){var x=u[u.length-1],I=z||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||S(I)?"[^".concat(oo(a),"]+?"):"(?:(?!".concat(oo(I),")[^").concat(oo(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),N=p("NAME"),k=p("PATTERN");if(N||k){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:$,suffix:"",pattern:k||R($),modifier:p("MODIFIER")||""});continue}var U=C||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var $=y(),v=p("NAME")||"",H=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(H?c++:""),pattern:v&&!H?R($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(io,"parse");function Ks(n,e){return gc(io(n,e),e)}i(Ks,"compile");function gc(n,e){e===void 0&&(e={});var t=fc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",S=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!S)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var C=o(h[R],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var N=S?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(gc,"tokensToFunction");function oo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(oo,"escapeString");function fc(n){return n&&n.sensitive?"":"i"}i(fc,"flags");var hc=he("zuplo:runtime"),ao=new TextEncoder,Js={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},yc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new uo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},uo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:S,singleEncode:R}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,N;(!c||!l)&&([C,N]=bc(this.url,this.headers)),this.service=c||C||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>S||!yc.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
|
|
56
|
+
`)}i(qs,"messagesToMultilineText");function Ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ze,"stringifyNonString");function Br(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ar(n):"unknown"}i(Br,"stringifyNonStringToText");import{importPKCS8 as ec,SignJWT as tc}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new tc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Us(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Gr("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Us,"exchangeIDTokenForGcpWorkloadToken");async function Hs({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return $s(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Hs,"generateServiceAccountIDToken");async function Zs(n,e,t){return Gr(n,{token:e,returnSecureToken:!0},t)}i(Zs,"exchangeFirebaseJwtForIdToken");async function Rn(n,e,t){return Gr(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Rn,"exchangeGgpJwtForIdToken");async function Gr(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return $s(n,r,t)}i(Gr,"fetchTokenFromBody");async function $s(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i($s,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ec(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function de(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await Fs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(de,"sendRemoteGlobalLog");async function Fs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:We(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Fs,"sendRemoteLogs");var nc=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Fs({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Pn,In=class{static{i(this,"RemoteLogTransport")}constructor(e){Pn||(Pn=new Y("remote-log-transport",1,nc(e)))}log(e,t){Pn.enqueue(e),t.waitUntil(Pn.waitUntilFlushed())}};var Vr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},rc="https://logging.googleapis.com/v2/entries:write?alt=json",Wr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:We(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(rc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await de({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await de({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var En="gcp";function xn(n){let e={allMessages:We(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Wr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(xn,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e.log(JSON.stringify(e))}};var Yr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Kr="__ddtags",Jr="__ddattr",Qr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),oc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Qr(r)):t.push(`${Qr(r)}:${Qr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Kr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Kr]!==void 0);a>-1&&(Object.assign(r,s[a][Kr]),s.splice(a,1));let u={},c=t.custom[Jr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Jr]!==void 0);l>-1&&(Object.assign(u,s[l][Jr]),s.splice(l,1));let d=We(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:oc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await de({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await de({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ic={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},js=i((n,e)=>t=>{let r={};return r.accountName=e.ACCOUNT_NAME,r.projectName=e.PROJECT_NAME,r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{logId:t.logId,timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ic[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var sc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=js(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Tn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Tn||(Tn=new Y("unified-log-transport",1,sc(e)))}async log(e,t){Tn.enqueue(e),t.waitUntil(Tn.waitUntilFlushed())}};var Xr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Xr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(sn);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Xr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(sn);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.isCloudflare&&(e.enableRuntimeUserLogs&&e.deploymentName&&e.remoteLogToken?r.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})):e.remoteLogToken&&e.loggingId&&r.push(new In({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy}))),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Xr("Gateway.createRequestLoggers");let a=new bn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var eo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Wt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},to=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Kt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof le))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new eo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new to(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Wt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Wt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var no;function zs(n){no=n}i(zs,"setGlobalZuploEventContext");function Cn(){if(no===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return no}i(Cn,"getGlobalZuploEventContext");function Bs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);rs.includes(o.toLowerCase())&&!os.includes(r.toLowerCase())&&t.delete(r)}t.delete(zi)}else ns.forEach(r=>{t.delete(r)});return t}i(Bs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),uc=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:Is(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[yn,fn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=uc(e.versions),r=new Kt(t);if(e.routes.length===0)return Sr(r,this),Mr(r,this),Nr(r,this),Es(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ns(r,this),_s(r,this)),Sr(r,this),Mr(r,this),Nr(r,this);for(let s of Ue)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),xs(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=Ms(s.stack)),o={cause:s}}}return E.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;zs(r);let a=Bs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(et,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(sr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let S=new On(e.headers),R=new te(u,{params:y.params}),C=new Sn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:S}),N=y.routeConfiguration.raw();ac.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(C,R);if(y.routeConfiguration===Dr&&Nt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=$.map(U=>U.routeConfiguration).filter(U=>U instanceof it)}try{if(Q.addLogger(C,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let v=await ps(R,C);if(v instanceof Response)return v;{let H=be.getContextExtensions(C);R=v,H.latestRequest=R}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let $=y.executableHandler;cc($,y,u),De("Gateway.handleRequest - call user handler");let U=await $(R,C);if(De("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let F;if(U.headers.get(et)===null&&!U.webSocket){let v=new Headers(U.headers);v.set(et,o),F=new Response(U.body,{status:U.status,statusText:U.statusText,headers:v,cf:U.cf})}else F=U;return F}catch($){return De("Gateway - error executing handler",$),$ instanceof A?(l.error($),d.warn($)):d.error($),await this.#i(R,C,$)}}};function cc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cc,"checkHandler");var Gs=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ht([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),Vs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new A(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(pr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(mr)??void 0}get city(){return this.#e.get(ar)??this.#e.get(Ji)??void 0}get continent(){return this.#e.get(ur)??this.#e.get(Qi)??void 0}get country(){return this.#e.get(cr)??this.#e.get(Yi)??void 0}get latitude(){return this.#e.get(dr)??this.#e.get(es)??void 0}get longitude(){return this.#e.get(lr)??this.#e.get(Xi)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(Wi)??this.#e.get(fr)??void 0}get metroCode(){return this.#e.get(Vi)??this.#e.get(hr)??void 0}get region(){return this.#e.get(Bi)??this.#e.get(yr)??void 0}get regionCode(){return this.#e.get(Gi)??this.#e.get(br)??void 0}get timezone(){return this.#e.get(Ki)??this.#e.get(wr)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Gs(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Vs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as lc}from"node:async_hooks";var Ws={request:new lc};var dc="Error initializing gateway. Check your configuration for errors or contact support.",pc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",ro=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(et)??e.headers.get(ji)??crypto.randomUUID(),s=e.headers.get(tt),a={requestId:o,rayId:s};return Ws.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await fs(this.runtimeInit)}catch(c){this.handleError(c,pc,e)}return as(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function mc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(mc,"lexer");function io(n,e){e===void 0&&(e={});for(var t=mc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(z){if(l<t.length&&t[l].type===z)return t[l++].value},"tryConsume"),h=i(function(z){var x=p(z);if(x!==void 0)return x;var I=t[l],M=I.type,ue=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ue,", expected ").concat(z))},"mustConsume"),y=i(function(){for(var z="",x;x=p("CHAR")||p("ESCAPED_CHAR");)z+=x;return z},"consumeText"),S=i(function(z){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(z.indexOf(M)>-1)return!0}return!1},"isSafe"),R=i(function(z){var x=u[u.length-1],I=z||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||S(I)?"[^".concat(oo(a),"]+?"):"(?:(?!".concat(oo(I),")[^").concat(oo(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),N=p("NAME"),k=p("PATTERN");if(N||k){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:$,suffix:"",pattern:k||R($),modifier:p("MODIFIER")||""});continue}var U=C||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var $=y(),v=p("NAME")||"",H=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(H?c++:""),pattern:v&&!H?R($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(io,"parse");function Ks(n,e){return gc(io(n,e),e)}i(Ks,"compile");function gc(n,e){e===void 0&&(e={});var t=fc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",S=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!S)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var C=o(h[R],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var N=S?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(gc,"tokensToFunction");function oo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(oo,"escapeString");function fc(n){return n&&n.sensitive?"":"i"}i(fc,"flags");var hc=he("zuplo:runtime"),ao=new TextEncoder,Js={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},yc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new uo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},uo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:S,singleEncode:R}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,N;(!c||!l)&&([C,N]=bc(this.url,this.headers)),this.service=c||C||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>S||!yc.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
|
|
57
57
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ys(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if($.has(U))return!1;$.add(U)}return!0}).map(U=>U.map(F=>Ys(encodeURIComponent(F)))).sort(([U,F],[v,H])=>U<v?-1:U>v?1:F<H?-1:F>H?1:0).map(U=>U.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Jt("AWS4"+this.secretAccessKey,e),s=await Jt(o,this.region),a=await Jt(s,this.service);r=await Jt(a,"aws4_request"),this.cache.set(t,r)}return so(await Jt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,so(await Qs(await this.canonicalString()))].join(`
|
|
58
58
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
59
59
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|