@zuplo/runtime 6.42.1 → 6.43.1

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.
@@ -23,4 +23,3 @@
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
25
  import{a as i}from"./chunk-PPV7V43C.js";var N=(e=>(e.Build="build-data",e.CorsPreflight="cors-preflight",e.DeveloperPortal="developer-portal",e.ZudokuPortal="zudoku-portal",e.DeveloperPortalLegacy="developer-portal-legacy",e.StripePlugin="stripe-plugin",e.EmptyGatewayCatchall="empty-gateway-catchall",e.Ping="ping",e.UnmatchedPath="unmatched-path",e))(N||{});function b(t){if(t.length>=255)throw new TypeError("Alphabet too long");let r=new Uint8Array(256);for(let e=0;e<r.length;e++)r[e]=255;for(let e=0;e<t.length;e++){let o=t.charAt(e),_=o.charCodeAt(0);if(r[_]!==255)throw new TypeError(o+" is ambiguous");r[_]=e}let n=t.length,f=t.charAt(0),m=Math.log(n)/Math.log(256),h=Math.log(256)/Math.log(n);function L(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let o=0,_=0,a=0,g=e.length;for(;a!==g&&e[a]===0;)a++,o++;let d=(g-a)*h+1>>>0,u=new Uint8Array(d);for(;a!==g;){let s=e[a],O=0;for(let p=d-1;(s!==0||O<_)&&p!==-1;p--,O++)s+=256*u[p]>>>0,u[p]=s%n>>>0,s=s/n>>>0;if(s!==0)throw new Error("Non-zero carry");_=O,a++}let c=d-_;for(;c!==d&&u[c]===0;)c++;let P=f.repeat(o);for(;c<d;++c)P+=t.charAt(u[c]);return P}i(L,"encode");function A(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let o=0,_=0,a=0;for(;e[o]===f;)_++,o++;let g=(e.length-o)*m+1>>>0,d=new Uint8Array(g);for(;e[o];){let s=r[e.charCodeAt(o)];if(s===255)return;let O=0;for(let p=g-1;(s!==0||O<a)&&p!==-1;p--,O++)s+=n*d[p]>>>0,d[p]=s%256>>>0,s=s/256>>>0;if(s!==0)throw new Error("Non-zero carry");a=O,o++}let u=g-a;for(;u!==g&&d[u]===0;)u++;let c=new Uint8Array(_+(g-u)),P=_;for(;u!==g;)c[P++]=d[u++];return c}i(A,"decodeUnsafe");function C(e){let o=A(e);if(o)return o;throw new Error("Non-base"+n+" character")}return i(C,"decode"),{encode:L,decodeUnsafe:A,decode:C}}i(b,"base");var T=b;var v="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=T(v);var U="2024-09-02",R=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function y(){return new l({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:U,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:R[U]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(y,"getMockEnvironment");var l=class t{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(r){this.#e||(this.#e=new t(r),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=y()),this.#e}constructor({build:r,runtime:n}){let f;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let m=new TextDecoder().decode(I.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),h=JSON.parse(m);for(let L of Object.keys(h))n[L]||(n[L]=h[L])}if(n.__ZUPLO_CONFIG){let m=atob(n.__ZUPLO_CONFIG);f=JSON.parse(m)}}catch(m){console.error("Failed to parse runtime configuration",m)}this.config=f??{},this.build=r,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var w=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function M(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!w.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(M,"isRestrictedEnvVariableName");function S(t){return!!t.startsWith("ZUPLO_")}i(S,"isZuploReadableEnvVariableName");var X=new Proxy({},{get(t,r){let n=String(r);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return l.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return l.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return l.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return l.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return l.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return l.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return l.instance.build.COMPATIBILITY_DATE}if(!(M(n)&&!S(n)))return l.instance.runtime[n]}});function ne(t,r,n){return`_${E(`${t}_${r}_${n}`)}`}i(ne,"getRawOperationDataIdentifierName");function re(t,r,n,f){return`_${E(t.toLowerCase())}_${r.toLowerCase()}_${n.toLowerCase()}_${f.toLowerCase()}`}i(re,"getIdForParameterSchema");function ie(t,r,n){return`_${E(t.toLowerCase())}_${r.toLowerCase()}_rb_${E(n.toLowerCase())}`}i(ie,"getIdForRequestBodySchema");function oe(t,r){return`_${E(t)}_${E(r)}`}i(oe,"getIdForRefSchema");function E(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}i(E,"sanitizedIdentifierName");export{l as a,N as b,M as c,S as d,X as e,ne as f,re as g,ie as h,oe as i,E as j};
26
- /*! For license information please see chunk-GPCONSBV.js.LEGAL.txt */
@@ -23,4 +23,3 @@
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
25
  var g=Object.create;var e=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=(b,a)=>e(b,"name",{value:a,configurable:!0});var n=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b,a,c,f)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of i(a))!k.call(b,d)&&d!==c&&e(b,d,{get:()=>a[d],enumerable:!(f=h(a,d))||f.enumerable});return b};var o=(b,a,c)=>(c=b!=null?g(j(b)):{},l(a||!b||!b.__esModule?e(c,"default",{value:b,enumerable:!0}):c,b));export{m as a,n as b,o as c};
26
- /*! For license information please see chunk-PPV7V43C.js.LEGAL.txt */
package/out/esm/index.js CHANGED
@@ -32,7 +32,7 @@ import{a as y,b as Fe,e as fe,f as Nu,g as lr,h as dr,i as Du,j as Mu}from"./chu
32
32
  `))):u=n.stylize("[Circular]","special")),es(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(hr,"formatProperty");function Qu(n,e){if(es(e))return n.stylize("undefined","undefined");if(ts(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Wu(e))return n.stylize(""+e,"number");if(Gu(e))return n.stylize(""+e,"boolean");if(ns(e))return n.stylize("null","null")}i(Qu,"formatPrimitive");function Yu(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(Yu,"reduceToSingleString");var os=i((n,...e)=>Yi(je,n,e),"format");var wr=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Qi(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=os(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},Rr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Xu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Xu,"extract");var gn;function be(n){let e=globalThis.DEBUG;gn||(gn=new Rr(Xu(e)));let t=new wr(gn,n);return gn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(be,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var tt=be("zuplo:runtime:external-service");function ec(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(ec,"getServiceAuth");async function is(n,e){let t=ec();if(t)if(tt(`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(y.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{tt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await tc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=ss(d.ENVIRONMENT_TYPE),h=await Pr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw tt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);tt(`Calling external service: ${c.toString()}`);let l=await fn(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 k("Could not connect to secure tunnel.");return l}else throw tt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw tt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(is,"externalServiceHandler");async function tc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=ss(r);tt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Pr(`${s}-${o}`),l=await Pr(`${s}-${a}-${u}`);return`${c}.${l}`}i(tc,"hashServiceName");async function Pr(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(Pr,"hashSegment");function ss(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(ss,"sanitizeEnvironmentType");var as=new Map;as.set("service:",is);var fn=globalThis.fetch;function Ir(n,e){let t=nc(e);if(typeof n=="string"){let r=new URL(n),o=as.get(r.protocol);return o?o(n,t):fn(n,t)}else return fn(n,t)}i(Ir,"internalFetch");globalThis.fetch=Ir;var nc=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 rc={fetch:Ir},z=rc;Function.prototype.toString=function(){return"[native code]"};var hn=globalThis,us=hn.caches;if(us){let n=us.open;hn.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete hn.caches.default,Object.freeze(hn.caches)}var cs=new Map,Er=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)})}},ze=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=cs.get(e);r||(r=new Er(t),cs.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 xr="__zuplo-expiry-header",Nt=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(xr);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(xr,`${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(xr,`${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 ze(r),this.#n=new Nt(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 Tr="__zuplo-expiry-header",Ar=class{static{i(this,"StreamingZoneCache")}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://streaming-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(Tr);if(!s){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(Tr,`${Date.now()+r*1e3}`);let s=new Response(t,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Tr]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),s=this.#o(e);await o.put(s,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var ls="zuplo-request-id",mt="zp-rid",Sr="zp-body-removed",nt="cf-ray",ds="x-real-ip",Cr="cf-ipcity",vr="cf-ipcontinent",Or="cf-ipcountry",kr="cf-iplongitude",Lr="cf-iplatitude",ps="cf-region",ms="cf-region-code",gs="cf-metro-code",fs="cf-postal-code",hs="cf-timezone",yn="zp-ipcity",bn="zp-ipcontinent",wn="zp-ipcountry",Rn="zp-iplongitude",Pn="zp-iplatitude",ys="true-client-ip",Dt="zp-asn",_r="zp-asorg",Nr="zp-colo",Mt="zp-postalcode",qt="zp-metrocode",Dr="zp-region",Ut="zp-regioncode",$t="zp-timezone",Mr="x-akamai-edgescape",bs=[Cr,vr,Or,kr,Lr,Dt,_r,Nr,Mt,qt,Dr,Ut,$t,Mr],ws=["zp-","cf-"],Rs=[mt,nt,Sr];var Ht=Symbol("zuplo_meters"),Zt=Symbol("zuplo_dynamic_meters"),In="system-logger";var te=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 Wc}from"@opentelemetry/api";import{SpanStatusCode as oc,trace as ic}from"@opentelemetry/api";import{SpanStatusCode as Hr,trace as Zr}from"@opentelemetry/api";var Ps=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Is(n){Ps=n}i(Is,"setTelemetryInitFunction");var Es=i(n=>Ps(n),"proxyHandler");var Be=class{static{i(this,"RuntimePlugin")}},me=class extends Be{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},En=class extends me{static{i(this,"MeteringPlugin")}},Ft=class extends Be{static{i(this,"TelemetryPlugin")}};var xn=new Set,xs=new Set;function f(n){xs.has(n)||(xs.add(n),xn.add(n))}i(f,"trackFeature");function Ts(){let n=[...xn];return xn.clear(),n}i(Ts,"getUnsentFeatures");function As(n){for(let e of n)xn.add(e)}i(As,"restoreFeatures");var jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},rt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await jt.problemResponseFormat(e,t,r)}};function Tn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Tn(t)}return Object.freeze(n)}i(Tn,"deepFreeze");var re=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 Tn(this.#e)}get params(){return Tn(this.#t)}user};var Fr={},Ue=[],qr=[],Ur=[],$r=[];var An={addPlugin(n){Ue.push(n)},addRequestHook(n){qr.push(n)},addResponseSendingHook(n){Ur.push(n)},addResponseSendingFinalHook(n){$r.push(n)}},Cs=i(async(n,e)=>{if(qr.length===0)return n;let t=Zr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of qr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Hr.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),vs=i(async(n,e,t)=>{if(Ur.length===0)return n;let r=Zr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Ur)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Hr.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Os=i(async(n,e,t)=>{if($r.length===0)return;let r=Zr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of $r)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Hr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ss=!1;async function ks(n){if(!Ss){n&&(f("runtime.extensions"),await n(An)),Fr.value=An;for(let e of Ue)if(e instanceof Ft){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});Is(t)}await Promise.all(Ue.map(async e=>{e instanceof me&&await e.initialize(An)})),jt.setProblemResponseFormat(An.problemResponseFormat),Ss=!0}}i(ks,"initializeRuntime");var jr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function zr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(jr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(jr.Json)||!e?JSON.stringify(n):n}i(zr,"serialize");function gt(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var ge=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>ic.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){let c=t.errorHandler(r,o,"Error executing request handler.",u);return a.setStatus({code:oc.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let S=a.pop();return S?S(o,s,t,u):await this.#e(async H=>{let Z=await r(H,s);return sc(Z)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new zt(o,l);s.dispatchEvent(p);let m=Ee.getContextExtensions(s),h=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return t.errorHandler(o,s,"Error retrieving mutableResponse",b)}try{I=await m.onResponseSending(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}try{I=await vs(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new Bt(o,I));try{await m.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await Os(l,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return I},"#toZuploPipeline")};function sc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(zr(n),{headers:{"content-type":"application/json"}})}i(sc,"resultToResponse");var Ge=class extends Be{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")};function _e(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}i(_e,"setZuploHeaders");var Sn=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)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=Ts(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=new Headers({"content-type":"application/json"});_e(l);let d=await z.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),As(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send metrics to Ellie.",t)}},"dispatchFunction")};var de=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.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var Re=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(nt)??void 0,c=n.headers.get(ys)??void 0,l=e.incomingRequestProperties,d;e.route instanceof de&&(d=e.route.systemRouteName);let p=Ee.getContextExtensions(e).latestRequest,m={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:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Sn(e)),Ue.forEach(I=>{if(I instanceof Ge){let b=I.getTransport();h.push(b)}}),h.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var Br=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=y.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ge({processors:[Re],handler:t,gateway:e}),o=new de({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Cn=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Cn||{}),Ls={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 ac={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"},Gr=ac;function uc(n){return`${new URL(n.url).pathname}`}i(uc,"instance");function cc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(nt);return r&&(t.rayId=r),t}i(cc,"trace");var lc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:uc(e),trace:cc(e,t),...r},additionalHeaders:o,statusText:Gr[n.status]}),"merge"),Vr=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?rt.format(e,t,r):rt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ls[e],...t}}},x=class extends Vr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=lc(this.getProblemFromStatus(e),t,r,o,s);return rt.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{toString:dc}=Object.prototype,{propertyIsEnumerable:pc}=Object.prototype;function Wr(n){return dc.call(n)}i(Wr,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function ft(n){return xe(n)&&n!==""}i(ft,"isNonEmptyString");function _s(n){return Wr(n)==="[object RegExp]"}i(_s,"isRegexp");function Ns(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>pc.call(n,e))]}i(Ns,"getOwnEnumerableKeys");function ot(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ot,"isObject");function Jr(n){return typeof n=="number"&&!isNaN(n)}i(Jr,"isNumber");function Kr(n){return n===!0||n===!1}i(Kr,"isBoolean");function Ds(n){return typeof n>"u"}i(Ds,"isUndefined");function Ms(n){return Ds(n)||n===null}i(Ms,"isUndefinedOrNull");function Gt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Gt,"isErrorLike");var qs=new Map;function Ve(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 g("Malformed input string");let e=qs.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 qs.set(n,r),r}i(Ve,"statusCodesStringToNumberArray");function $e(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i($e,"getValueFromRequestUser");function it(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(it,"parseValueToStringArray");function Us(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!ot(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ft(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Jr(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Kr(t.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Qr(t,"allowedHeaders"),o=Qr(t,"allowedMethods"),s=Qr(t,"exposeHeaders"),a;try{a=it(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Us,"parseCorsPolicies");function Qr(n,e){let t;if(n[e]!==void 0)try{t=it(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Qr,"parseOptionalProperty");var vn=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"),On=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 Yr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(c,l);if(!m)return x.notFound(a,u);let h=m.routeConfiguration,I=mc(l,d,p,h,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),x.notFound(a,u))},"optionsHandler"),o=new ge({processors:[Re],handler:r,gateway:e}),s=new de({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),mc=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=vn(a.allowedOrigins,t);return u?{isValid:!0,headers:On(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var $s=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ge({processors:[Re],handler:t,gateway:e}),o=new de({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 We=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.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var gc=new de({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Hs=i((n,e)=>{let t=i(async(o,s)=>{let a=Fr.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof We)}})}return x.notFound(o,s)},"notFoundHandler"),r=new ge({processors:[Re],handler:t,gateway:e});n.addRoute(gc,r.execute)},"registerNotMatchedHandler");var fc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Zs=i(n=>{fc.forEach(e=>n.delete(e))},"stripCorsHeaders"),kn=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 Zs(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=hc(o,t.routeData.corsPolicies),u=yc(n,a),c=new Headers(s.headers);return Zs(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"),hc=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),yc=i((n,e)=>{let t=vn(e.allowedOrigins,n.headers.get("origin"));return t?On(e,t):{}},"getCorsHeaders");var Xr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ge({processors:[kn],handler:t,gateway:e}),o=new de({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Fs,trace as js}from"@opentelemetry/api";var He={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 Ln=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new k(`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 Ln{static{i(this,"InboundPolicy")}},Je=class extends Ln{static{i(this,"OutboundPolicy")}};var no=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)}},ro=class extends Je{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},eo=new Map;function Vt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!eo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new no(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);eo.set(a.name,c)}),t.map(s=>{let a=eo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Vt,"getInboundPolicyInstances");var to=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!to.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Je)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new ro(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);to.set(a.name,c)}),t.map(s=>{let a=to.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Wt,"getOutboundPolicyInstances");var oo=i(n=>async(e,t)=>{let r=Ee.getContextExtensions(t),o=js.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 re||p instanceof Response)return d.end(),p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Fs.ERROR}),d.recordException(m),m}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),io=i(n=>async(e,t,r)=>{let o=js.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(He.PolicyName,c.policyName),d.setAttribute(He.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Fs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),_n=i(async(n,e,t,r)=>{let o=Vt(e.route,t.routeData.policies),s=Wt(e.route,t.routeData.policies);return Bs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function zs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Bs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(zs,"createInternalPolicyProcessor");async function Bs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=oo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=io(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return o.errorHandler(n,e,"Error executing policies",u)}}i(Bs,"executePolicyProcessor");var Js=_u(Ws(),1);function Ks(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Js.parse)(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 Qs="/__zuplo/dev-portal",Cc="dev-portal-id",vc="dev-portal-host",Oc="zp-account",kc="zp-project",Lc="dev-portal-build",_c=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Yu,"reduceToSingleString");var os=i((n,...e)=>Yi(je,n,e),"format");var wr=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Qi(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=os(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},Rr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Xu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Xu,"extract");var gn;function be(n){let e=globalThis.DEBUG;gn||(gn=new Rr(Xu(e)));let t=new wr(gn,n);return gn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(be,"debug");var K=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var tt=be("zuplo:runtime:external-service");function ec(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(ec,"getServiceAuth");async function is(n,e){let t=ec();if(t)if(tt(`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(y.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{tt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await tc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=ss(d.ENVIRONMENT_TYPE),h=await Pr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw tt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);tt(`Calling external service: ${c.toString()}`);let l=await fn(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 k("Could not connect to secure tunnel.");return l}else throw tt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw tt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(is,"externalServiceHandler");async function tc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=ss(r);tt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Pr(`${s}-${o}`),l=await Pr(`${s}-${a}-${u}`);return`${c}.${l}`}i(tc,"hashServiceName");async function Pr(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(Pr,"hashSegment");function ss(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(ss,"sanitizeEnvironmentType");var as=new Map;as.set("service:",is);var fn=globalThis.fetch;function Ir(n,e){let t=nc(e);if(typeof n=="string"){let r=new URL(n),o=as.get(r.protocol);return o?o(n,t):fn(n,t)}else return fn(n,t)}i(Ir,"internalFetch");globalThis.fetch=Ir;var nc=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 rc={fetch:Ir},z=rc;Function.prototype.toString=function(){return"[native code]"};var hn=globalThis,us=hn.caches;if(us){let n=us.open;hn.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete hn.caches.default,Object.freeze(hn.caches)}var cs=new Map,Er=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)})}},ze=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=cs.get(e);r||(r=new Er(t),cs.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 xr="__zuplo-expiry-header",Nt=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(xr);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(xr,`${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(xr,`${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 ze(r),this.#n=new Nt(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 Tr="__zuplo-expiry-header",Ar=class{static{i(this,"StreamingZoneCache")}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://streaming-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(Tr);if(!s){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(Tr,`${Date.now()+r*1e3}`);let s=new Response(t,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Tr]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),s=this.#o(e);await o.put(s,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var ls="zuplo-request-id",mt="zp-rid",Sr="zp-body-removed",nt="cf-ray",ds="x-real-ip",Cr="cf-ipcity",vr="cf-ipcontinent",Or="cf-ipcountry",kr="cf-iplongitude",Lr="cf-iplatitude",ps="cf-region",ms="cf-region-code",gs="cf-metro-code",fs="cf-postal-code",hs="cf-timezone",yn="zp-ipcity",bn="zp-ipcontinent",wn="zp-ipcountry",Rn="zp-iplongitude",Pn="zp-iplatitude",ys="true-client-ip",Dt="zp-asn",_r="zp-asorg",Nr="zp-colo",Mt="zp-postalcode",qt="zp-metrocode",Dr="zp-region",Ut="zp-regioncode",$t="zp-timezone",Mr="x-akamai-edgescape",bs=[Cr,vr,Or,kr,Lr,Dt,_r,Nr,Mt,qt,Dr,Ut,$t,Mr],ws=["zp-","cf-"],Rs=[mt,nt,Sr];var Ht=Symbol("zuplo_meters"),Zt=Symbol("zuplo_dynamic_meters"),In="system-logger";var te=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 Wc}from"@opentelemetry/api";import{SpanStatusCode as oc,trace as ic}from"@opentelemetry/api";import{SpanStatusCode as Hr,trace as Zr}from"@opentelemetry/api";var Ps=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Is(n){Ps=n}i(Is,"setTelemetryInitFunction");var Es=i(n=>Ps(n),"proxyHandler");var Be=class{static{i(this,"RuntimePlugin")}},me=class extends Be{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},En=class extends me{static{i(this,"MeteringPlugin")}},Ft=class extends Be{static{i(this,"TelemetryPlugin")}};var xn=new Set,xs=new Set;function f(n){xs.has(n)||(xs.add(n),xn.add(n))}i(f,"trackFeature");function Ts(){let n=[...xn];return xn.clear(),n}i(Ts,"getUnsentFeatures");function As(n){for(let e of n)xn.add(e)}i(As,"restoreFeatures");var jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},rt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await jt.problemResponseFormat(e,t,r)}};function Tn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Tn(t)}return Object.freeze(n)}i(Tn,"deepFreeze");var re=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 Tn(this.#e)}get params(){return Tn(this.#t)}user};var Fr={},Ue=[],qr=[],Ur=[],$r=[];var An={addPlugin(n){Ue.push(n)},addRequestHook(n){qr.push(n)},addResponseSendingHook(n){Ur.push(n)},addResponseSendingFinalHook(n){$r.push(n)}},Cs=i(async(n,e)=>{if(qr.length===0)return n;let t=Zr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of qr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Hr.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),vs=i(async(n,e,t)=>{if(Ur.length===0)return n;let r=Zr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Ur)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Hr.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Os=i(async(n,e,t)=>{if($r.length===0)return;let r=Zr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of $r)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Hr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ss=!1;async function ks(n){if(!Ss){n&&(f("runtime.extensions"),await n(An)),Fr.value=An;for(let e of Ue)if(e instanceof Ft){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});Is(t)}await Promise.all(Ue.map(async e=>{e instanceof me&&await e.initialize(An)})),jt.setProblemResponseFormat(An.problemResponseFormat),Ss=!0}}i(ks,"initializeRuntime");var jr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function zr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(jr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(jr.Json)||!e?JSON.stringify(n):n}i(zr,"serialize");function gt(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var ge=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>ic.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){let c=t.errorHandler(r,o,"Error executing request handler.",u);return a.setStatus({code:oc.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let S=a.pop();return S?S(o,s,t,u):await this.#e(async H=>{let Z=await r(H,s);return sc(Z)},t)(b,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new zt(o,l);s.dispatchEvent(p);let m=Ee.getContextExtensions(s),h=m.latestRequest,I;try{I=await p.mutableResponse}catch(b){return t.errorHandler(o,s,"Error retrieving mutableResponse",b)}try{I=await m.onResponseSending(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}try{I=await vs(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new Bt(o,I));try{await m.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await Os(l,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return I},"#toZuploPipeline")};function sc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(zr(n),{headers:{"content-type":"application/json"}})}i(sc,"resultToResponse");var Ge=class extends Be{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")};function _e(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}i(_e,"setZuploHeaders");var Sn=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new Y("zuplo-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)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=Ts(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=new Headers({"content-type":"application/json"});_e(l);let d=await z.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),As(u)}}catch(t){Q.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var de=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.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var Re=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(nt)??void 0,c=n.headers.get(ys)??void 0,l=e.incomingRequestProperties,d;e.route instanceof de&&(d=e.route.systemRouteName);let p=Ee.getContextExtensions(e).latestRequest,m={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:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new Sn(e)),Ue.forEach(I=>{if(I instanceof Ge){let b=I.getTransport();h.push(b)}}),h.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var Br=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=y.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ge({processors:[Re],handler:t,gateway:e}),o=new de({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Cn=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Cn||{}),Ls={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 ac={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"},Gr=ac;function uc(n){return`${new URL(n.url).pathname}`}i(uc,"instance");function cc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(nt);return r&&(t.rayId=r),t}i(cc,"trace");var lc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:uc(e),trace:cc(e,t),...r},additionalHeaders:o,statusText:Gr[n.status]}),"merge"),Vr=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?rt.format(e,t,r):rt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ls[e],...t}}},x=class extends Vr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=lc(this.getProblemFromStatus(e),t,r,o,s);return rt.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{toString:dc}=Object.prototype,{propertyIsEnumerable:pc}=Object.prototype;function Wr(n){return dc.call(n)}i(Wr,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function ft(n){return xe(n)&&n!==""}i(ft,"isNonEmptyString");function _s(n){return Wr(n)==="[object RegExp]"}i(_s,"isRegexp");function Ns(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>pc.call(n,e))]}i(Ns,"getOwnEnumerableKeys");function ot(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(ot,"isObject");function Jr(n){return typeof n=="number"&&!isNaN(n)}i(Jr,"isNumber");function Kr(n){return n===!0||n===!1}i(Kr,"isBoolean");function Ds(n){return typeof n>"u"}i(Ds,"isUndefined");function Ms(n){return Ds(n)||n===null}i(Ms,"isUndefinedOrNull");function Gt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Gt,"isErrorLike");var qs=new Map;function Ve(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 g("Malformed input string");let e=qs.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 qs.set(n,r),r}i(Ve,"statusCodesStringToNumberArray");function $e(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i($e,"getValueFromRequestUser");function it(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(it,"parseValueToStringArray");function Us(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!ot(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ft(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Jr(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Kr(t.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Qr(t,"allowedHeaders"),o=Qr(t,"allowedMethods"),s=Qr(t,"exposeHeaders"),a;try{a=it(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Us,"parseCorsPolicies");function Qr(n,e){let t;if(n[e]!==void 0)try{t=it(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Qr,"parseOptionalProperty");var vn=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"),On=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 Yr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(c,l);if(!m)return x.notFound(a,u);let h=m.routeConfiguration,I=mc(l,d,p,h,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),x.notFound(a,u))},"optionsHandler"),o=new ge({processors:[Re],handler:r,gateway:e}),s=new de({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),mc=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=vn(a.allowedOrigins,t);return u?{isValid:!0,headers:On(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var $s=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ge({processors:[Re],handler:t,gateway:e}),o=new de({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 We=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.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var gc=new de({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Hs=i((n,e)=>{let t=i(async(o,s)=>{let a=Fr.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof We)}})}return x.notFound(o,s)},"notFoundHandler"),r=new ge({processors:[Re],handler:t,gateway:e});n.addRoute(gc,r.execute)},"registerNotMatchedHandler");var fc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Zs=i(n=>{fc.forEach(e=>n.delete(e))},"stripCorsHeaders"),kn=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 Zs(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=hc(o,t.routeData.corsPolicies),u=yc(n,a),c=new Headers(s.headers);return Zs(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"),hc=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),yc=i((n,e)=>{let t=vn(e.allowedOrigins,n.headers.get("origin"));return t?On(e,t):{}},"getCorsHeaders");var Xr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ge({processors:[kn],handler:t,gateway:e}),o=new de({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Fs,trace as js}from"@opentelemetry/api";var He={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 Ln=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new k(`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 Ln{static{i(this,"InboundPolicy")}},Je=class extends Ln{static{i(this,"OutboundPolicy")}};var no=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)}},ro=class extends Je{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},eo=new Map;function Vt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!eo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new no(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);eo.set(a.name,c)}),t.map(s=>{let a=eo.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Vt,"getInboundPolicyInstances");var to=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!to.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Je)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new ro(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);to.set(a.name,c)}),t.map(s=>{let a=to.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Wt,"getOutboundPolicyInstances");var oo=i(n=>async(e,t)=>{let r=Ee.getContextExtensions(t),o=js.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 re||p instanceof Response)return d.end(),p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Fs.ERROR}),d.recordException(m),m}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),io=i(n=>async(e,t,r)=>{let o=js.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(He.PolicyName,c.policyName),d.setAttribute(He.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Fs.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),_n=i(async(n,e,t,r)=>{let o=Vt(e.route,t.routeData.policies),s=Wt(e.route,t.routeData.policies);return Bs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function zs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Bs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(zs,"createInternalPolicyProcessor");async function Bs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=oo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=io(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return o.errorHandler(n,e,"Error executing policies",u)}}i(Bs,"executePolicyProcessor");var Js=_u(Ws(),1);function Ks(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Js.parse)(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 Qs="/__zuplo/dev-portal",Cc="dev-portal-id",vc="dev-portal-host",Oc="zp-account",kc="zp-project",Lc="dev-portal-build",_c=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -23,4 +23,3 @@
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
25
  import{c as e,d as t,f as a,g as o,h as r,i,j as n}from"../chunk-GPCONSBV.js";import"../chunk-PPV7V43C.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
26
- /*! For license information please see index.js.LEGAL.txt */
@@ -23,4 +23,3 @@
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
25
  import{a as n}from"../chunk-PPV7V43C.js";function a(s={request:new Request("https://api.example.com")}){let e=[];function o(t){e.push(Promise.resolve(t))}return n(o,"waitUntil"),{context:new i({event:{waitUntil:o},route:s.route}),invokeResponse:n(async()=>{await Promise.all(e)},"invokeResponse")}}n(a,"createMockContext");var l={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:n(()=>({}),"raw")},i=class extends EventTarget{static{n(this,"MockZuploContext")}#e;requestId;log;route;custom;incomingRequestProperties;constructor({event:e,route:o=l}){super(),this.requestId=crypto.randomUUID(),this.log={info:console.info,log:console.log,debug:console.debug,warn:console.warn,error:console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0},this.#e=e}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let u=n(t=>{try{typeof o=="function"?o(t):o.handleEvent(t)}catch(d){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),d}},"wrapped");super.addEventListener(e,u,r)}};export{i as MockZuploContext,a as createMockContext};
26
- /*! For license information please see index.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.42.1",
4
+ "version": "6.43.1",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
8
8
  ".": {
9
- "import": "./out/esm/index.js",
10
- "types": "./out/types/index.d.ts"
9
+ "types": "./out/types/index.d.ts",
10
+ "import": "./out/esm/index.js"
11
11
  },
12
12
  "./mocks": {
13
- "import": "./out/esm/mocks/index.js",
14
- "types": "./out/types/mocks/index.d.ts"
13
+ "types": "./out/types/mocks/index.d.ts",
14
+ "import": "./out/esm/mocks/index.js"
15
15
  }
16
16
  },
17
17
  "license": "SEE LICENSE IN LICENSE.txt",
File without changes
File without changes
File without changes
File without changes