@zuplo/runtime 6.51.12 → 6.51.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/esm/index.js CHANGED
@@ -62,7 +62,7 @@ import{a as y,b as bt,e as Se,f as Kl,g as Ao,h as _o,i as Ql,j as Yl}from"./chu
62
62
  `,pad:u,indent:u+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(h=>{if(c.inlineCharacterLimit===void 0)return h;let x=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return x.length<=c.inlineCharacterLimit?x:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
63
  `).replace(new RegExp(p.pad,"g"),u).replace(new RegExp(p.indent,"g"),u+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Rc(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((x,b)=>{let P=a.length-1===b?p.newline:","+p.newlineOrSpace,N=i(x,c,u+d,l+1);return c.transform&&(N=c.transform(a,b,N)),p.indent+N+P}).join("")+p.pad+"]";return r.pop(),m(h)}if(Zt(a)){let h=vc(a);if(c.filter&&(h=h.filter(b=>c.filter?.(a,b))),h.length===0)return"{}";r.push(a);let x="{"+p.newline+h.map((b,P)=>{let N=h.length-1===P?p.newline:","+p.newlineOrSpace,A=typeof b=="symbol",B=!A&&/^[a-z$_][$\w]*$/i.test(b),$=A||B?b:i(b,c,"",l+1),G=i(a[b],c,u+d,l+1);return c.transform&&(G=c.transform(a,b,G)),p.indent+String($)+": "+G+N}).join("")+p.pad+"}";return r.pop(),m(x)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
64
64
  `?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(Wr,"stringifyObject");function $e(n){return jc(qt(n))}s($e,"serializeMessage");function nt(n){return n.map(e=>$e(e))}s(nt,"serializeMessages");function ln(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:jc(qt(e))}s(ln,"extractBestMessage");function Fc(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Qn(t))if(t.stack)e.push(t.stack);else{let r=Wr(qt(t));e.push(r)}else if(typeof t=="object"){let r=Wr(t);e.push(r)}else{let r=Ci(t);e.push(r)}}),e.join(`
65
- `)}s(Fc,"messagesToMultilineText");function jc(n){return typeof n=="string"?n:JSON.stringify(n)}s(jc,"stringifyNonString");function Ci(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?mi(n):"unknown"}s(Ci,"stringifyNonStringToText");import{SignJWT as op,importPKCS8 as ip}from"jose";async function Oe(n,e,t){for(let r=0;r<=n.retries;r++){let o=j.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Oe,"fetchRetry");async function Be({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new op(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Be,"getTokenFromGcpServiceAccount");async function zc(n,e,t){if(!n.startsWith("projects/"))throw new f(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Oi("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(zc,"exchangeIDTokenForGcpWorkloadToken");async function Bc({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Vc(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(Bc,"generateServiceAccountIDToken");async function Gc(n,e,t){return Oi(n,{token:e,returnSecureToken:!0},t)}s(Gc,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return Oi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(dn,"exchangeGgpJwtForIdToken");async function Oi(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Vc(n,r,t)}s(Oi,"fetchTokenFromBody");async function Vc(n,e,t){let r=await Oe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),c=JSON.parse(a);i={cause:c.error_description??c.error??c}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Vc,"fetchToken");var Le=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ip(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var sp={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Wc=s(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:sp[e.level],body:nt(e.messages),attributes:t}},"unifiedFormatter");async function se(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Jc(y.instance,[r])}catch(r){console.error(r)}}s(se,"sendRemoteGlobalLog");async function Jc(n,e){let t=Wc(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});Xe(r),await j.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(Jc,"sendLogs");var ap=s(n=>async e=>{e.length!==0&&await Jc(n,e)},"dispatchFunction"),Jr,nr=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jr||(Jr=new ie("unified-log-transport",1,ap(e)))}log(e,t){Jr.enqueue(e),t.waitUntil(Jr.waitUntilFlushed())}};var Ai=class extends Re{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new rr(this.options)}},cp="https://logging.googleapis.com/v2/entries:write?alt=json",_i={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},rr=class{static{s(this,"GoogleLogTransport")}constructor(e){g("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Le.init(this.#e)}log(e,t){if(!this.#t)throw new ae("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:nt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_i[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=ln(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length===0)return;this.#t||(this.#t=await Le.init(this.#e));let t=await Be({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await j.fetch(cp,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await se({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("google-log-transport",1,this.dispatchFunction)};var Kr="gcp";function Qr(n){let e={allMessages:nt(n.messages)},t="zuplo-production",r=ln(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:_i[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(Qr,"gcpLogFormat");var or=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level](Qr(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:nt(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var Mi=class extends Re{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ir(this.options)}},ki="__ddtags",Li="__ddattr",Ni=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),up=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ni(r)):t.push(`${Ni(r)}:${Ni(o.toString())}`)}),t.join(",")},"formatTags"),ir=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},i=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[ki];l&&typeof l=="object"&&(g("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[ki]!==void 0);d>-1&&(Object.assign(r,i[d][ki]),i.splice(d,1));let p=t.custom[Li];p&&typeof p=="object"&&(g("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[Li]!==void 0);m>-1&&(Object.assign(o,i[m][Li]),i.splice(m,1))}let a=nt(i),c={...e,activityId:e.requestId,trace:e.requestId},u=Object.assign({message:{...c,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ln(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:up(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(u),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await se({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("data-dog-transport",10,this.dispatchFunction)};var sr=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Qr(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Di=Ce("zuplo:logging"),Yr=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Di("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Lr);return i?o.push(new sr(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new nr(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new er(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Di("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Lr);if(a&&a.captureUserLogs===!0?r.push(new sr(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new nr(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new rr({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){g("logging.datadog.legacy-initialization");let c=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ir({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return at.forEach(c=>{c instanceof Re&&r.push(c.getTransport())}),await Promise.all(r.map(async c=>{c.init&&await c.init()})),new er(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i,a){Di("Gateway.createRequestLoggers");let c=new Vr(r,o,i,a),u=new tr(e,t,this.systemCoreLogger,c);return{userRequestLogger:new tr(e,t,this.userCoreLogger,c),systemRequestLogger:u}}};var pn=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Xr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}};var Zi=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new ae(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},eo=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof xt||e instanceof xe))throw new ae("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new Zi(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Xr(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new f(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let i=o.urlPattern.exec({pathname:e});if(i!==null)return new pn(o.config,o.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],i=o.urlPattern.exec({pathname:e});if(i!==null){let a=new pn(o.config,o.executableHandler,i.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as lp}from"node:async_hooks";var to={context:new lp};var qi;function Kc(n){qi=n}s(Kc,"setGlobalZuploEventContext");function It(){if(qi===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return qi}s(It,"getGlobalZuploEventContext");function Qc({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ac.includes(o.toLowerCase())&&!cc.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qa)}else sc.forEach(r=>{t.delete(r)});return t}s(Qc,"normalizeIncomingRequestHeaders");var Et=Ce("zuplo:runtime"),Ie=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Et("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Et("Gateway.initialize"),!n.#e){let i=await Yr.init(r),a=await e(),c={...a,corsPolicies:Ec(a.corsPolicies)},u=new n(c,t,i,o);n.#e=u}if(!n.#e)throw new ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Et("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new ae("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Br,jr,ke];setupRoutes=s(()=>{Et("Gateway.setupRoutes");let e=this.routeData,t=new eo;if(e.routes.length===0)return li(t,this),bi(t,this),yi(t,this),Tc(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(Uc(t,this),$c(t,this)),li(t,this),bi(t,this),yi(t,this);for(let i of at)i instanceof Ee&&i.registerRoutes(t,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let c=new Te({processors:this.#r,handler:a,gateway:this}),u=new xt(i);t.addRoute(u,c.execute)}),Sc(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Et("Gateway.internalErrorResponse"),t.log.error(r,o);let i={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)i=o.extensionMembers;else if(o.cause){let a=qt(o.cause);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}else{let a=qt(o);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}return T.internalServerError(e,t,{detail:o.message,...i})}async handleRequest(e,t,r){let o=e.headers.get(an)??e.headers.get(Ka)??r?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mt);Kc(t);let a=Qc({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(an,o);let c=new Request(e,{headers:a});if(["GET","HEAD"].includes(c.method)&&c.body){let B=new Headers(c.headers);B.set(Vo,"true"),c=new Request(c,{headers:B,body:null})}c=await hc(c);let u=new URL(c.url),l=u.pathname,d=this.#n.lookup(l,c.method);if(!d)throw new ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,i,t,p,c,d.routeConfiguration);cn(u)||m.debug(`Request received '${u.pathname}'`,{method:c.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let x=new no(e.headers),b=new ue(c,{params:d.params}),P=new ro({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:x,parentContext:r?.parentContext}),N=to.context.getStore();N&&(N.context=P);let A=d.routeConfiguration.raw();dp.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[lt.RoutePathPattern]:P.route.pathPattern,[lt.RouteOperationId]:A.operationId,[lt.RouteTrace]:A["x-zuplo-trace"],[lt.RouteSystem]:cn(u)?!0:void 0}),_e.initialize(P,b);try{if(ne.addLogger(P,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!cn(u):!u.pathname.startsWith("/__zuplo")){let O=await mc(b,P);if(O instanceof Response)return O;{let F=_e.getContextExtensions(P);b=O,F.latestRequest=b}}let B=d.executableHandler;pp(B,d,c),Et("Gateway.handleRequest - call user handler");let $=await B(b,P);if(Et("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let G;if($.headers.get(an)===null&&!$.webSocket){let O=new Headers($.headers);O.set(an,o),G=new Response($.body,{status:$.status,statusText:$.statusText,headers:O,cf:$.cf})}else G=$;return G}catch(B){return B instanceof k?(m.error(B),h.warn(B)):h.error(B),await this.errorHandler(b,P,"Error executing handler",B)}}};function pp(n,e,t){if(Et("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(pp,"checkHandler");import{SpanStatusCode as Yc,trace as Xc}from"@opentelemetry/api";var eu=s(async(n,e,t)=>{let r=Ie.instance.routeData.policies,o=Yn([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let i=o[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,t);if(l instanceof Request||l instanceof ue||l instanceof Response)return l instanceof Response||l instanceof ue?l:new ue(l);{let d=new f(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Yc.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),tu=s(async(n,e,t,r)=>{let o=Ie.instance.routeData.policies,i=Xn([n],o);if(i.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=i[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new f(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Yc.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function mp(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[i,a]=o.split("=");i&&a&&(r[i.trim()]=a.trim())}),r.asnum&&(e[Un]=r.asnum),r.zip&&(e[Hn]=r.zip.split("+")[0]),r.dma&&(e[Fn]=r.dma),r.region_code&&(e[jn]=r.region_code),r.timezone&&(e[zn]=r.timezone),r.city&&(e[Cr]=r.city),r.continent&&(e[Or]=r.continent),r.country_code&&(e[Ar]=r.country_code),r.long&&(e[_r]=r.long),r.lat&&(e[kr]=r.lat),e}catch{return{}}}s(mp,"parseEdgeScapeHeader");function nu(n,e){let t=mp(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}s(nu,"setZpHeadersFromAkamaiEdgeScapeHeader");var no=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(ni);if(t){let r=new Headers(e);nu(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Un);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Xo)??void 0}get city(){return this.#e.get(Wo)??this.#e.get(Cr)??void 0}get continent(){return this.#e.get(Jo)??this.#e.get(Or)??void 0}get country(){return this.#e.get(Ko)??this.#e.get(Ar)??void 0}get latitude(){return this.#e.get(Yo)??this.#e.get(kr)??void 0}get longitude(){return this.#e.get(Qo)??this.#e.get(_r)??void 0}get colo(){return this.#e.get(ei)??void 0}get postalCode(){return this.#e.get(tc)??this.#e.get(Hn)??void 0}get metroCode(){return this.#e.get(ec)??this.#e.get(Fn)??void 0}get region(){return this.#e.get(Ya)??this.#e.get(ti)??void 0}get regionCode(){return this.#e.get(Xa)??this.#e.get(jn)??void 0}get timezone(){return this.#e.get(nc)??this.#e.get(zn)??void 0}get httpProtocol(){return this.#e.get(ic)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function Tt(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}s(Tt,"createRewriteContext");var Jn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Kn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},_e=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=s(async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o},"onResponseSending");onHandlerResponse=s(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},ro=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=o,this.invokeInboundPolicy=(u,l)=>eu(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>tu(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=new ue(u,l);return Ie.instance.handleRequest(d,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{_e.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{_e.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fp="Error initializing gateway. Check your configuration for errors or contact support.",gp="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",$i=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=s(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await yc(this.runtimeInit)}catch(i){this.handleError(i,gp,e)}return dc(s(async(i,a)=>{let c;try{c=await Ie.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,fp,i)}let u={context:void 0};return to.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function hp(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var c=1,u="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){u+=n[i++]+n[i++];continue}if(n[i]===")"){if(c--,c===0){i++;break}}else if(n[i]==="("&&(c++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));u+=n[i++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(t));if(!u)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:u}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(hp,"lexer");function Hi(n,e){e===void 0&&(e={});for(var t=hp(n),r=e.prefixes,o=r===void 0?"./":r,i=e.delimiter,a=i===void 0?"/#?":i,c=[],u=0,l=0,d="",p=s(function(V){if(l<t.length&&t[l].type===V)return t[l++].value},"tryConsume"),m=s(function(V){var S=p(V);if(S!==void 0)return S;var E=t[l],U=E.type,we=E.index;throw new TypeError("Unexpected ".concat(U," at ").concat(we,", expected ").concat(V))},"mustConsume"),h=s(function(){for(var V="",S;S=p("CHAR")||p("ESCAPED_CHAR");)V+=S;return V},"consumeText"),x=s(function(V){for(var S=0,E=a;S<E.length;S++){var U=E[S];if(V.indexOf(U)>-1)return!0}return!1},"isSafe"),b=s(function(V){var S=c[c.length-1],E=V||(S&&typeof S=="string"?S:"");if(S&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(S.name,'"'));return!E||x(E)?"[^".concat(Ui(a),"]+?"):"(?:(?!".concat(Ui(E),")[^").concat(Ui(a),"])+?")},"safePattern");l<t.length;){var P=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var B=P||"";o.indexOf(B)===-1&&(d+=B,B=""),d&&(c.push(d),d=""),c.push({name:N||u++,prefix:B,suffix:"",pattern:A||b(B),modifier:p("MODIFIER")||""});continue}var $=P||p("ESCAPED_CHAR");if($){d+=$;continue}d&&(c.push(d),d="");var G=p("OPEN");if(G){var B=h(),O=p("NAME")||"",F=p("PATTERN")||"",Y=h();m("CLOSE"),c.push({name:O||(F?u++:""),pattern:O&&!F?b(B):F,prefix:B,suffix:Y,modifier:p("MODIFIER")||""});continue}m("END")}return c}s(Hi,"parse");function ru(n,e){return yp(Hi(n,e),e)}s(ru,"compile");function yp(n,e){e===void 0&&(e={});var t=bp(e),r=e.encode,o=r===void 0?function(u){return u}:r,i=e.validate,a=i===void 0?!0:i,c=n.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),t)});return function(u){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",x=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!x)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var P=o(m[b],p);if(a&&!c[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var P=o(String(m),p);if(a&&!c[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!h){var N=x?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(yp,"tokensToFunction");function Ui(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Ui,"escapeString");function bp(n){return n&&n.sensitive?"":"i"}s(bp,"flags");var wp=Ce("zuplo:runtime"),ji=new TextEncoder,ou={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Rp=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],mn=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,t){let r=new zi(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){wp("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=j.fetch(o,i);if(r===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},zi=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:x,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=c;let P,N;(!u||!l)&&([P,N]=vp(this.url,this.headers)),this.service=u||P||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter($=>x||!Rp.includes($)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map($=>$+":"+($==="host"?this.url.host:(this.headers.get($)||"").replace(/\s+/g," "))).join(`
65
+ `)}s(Fc,"messagesToMultilineText");function jc(n){return typeof n=="string"?n:JSON.stringify(n)}s(jc,"stringifyNonString");function Ci(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?mi(n):"unknown"}s(Ci,"stringifyNonStringToText");import{SignJWT as op,importPKCS8 as ip}from"jose";async function Oe(n,e,t){for(let r=0;r<=n.retries;r++){let o=j.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Oe,"fetchRetry");async function Be({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new op(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Be,"getTokenFromGcpServiceAccount");async function zc(n,e,t){if(!n.startsWith("projects/"))throw new f(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Oi("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(zc,"exchangeIDTokenForGcpWorkloadToken");async function Bc({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Vc(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(Bc,"generateServiceAccountIDToken");async function Gc(n,e,t){return Oi(n,{token:e,returnSecureToken:!0},t)}s(Gc,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return Oi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(dn,"exchangeGgpJwtForIdToken");async function Oi(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Vc(n,r,t)}s(Oi,"fetchTokenFromBody");async function Vc(n,e,t){let r=await Oe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),c=JSON.parse(a);i={cause:c.error_description??c.error??c}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Vc,"fetchToken");var Le=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ip(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var sp={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Wc=s(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:sp[e.level],body:nt(e.messages),attributes:t}},"unifiedFormatter");async function se(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Jc(y.instance,[r])}catch(r){console.error(r)}}s(se,"sendRemoteGlobalLog");async function Jc(n,e){let t=Wc(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});Xe(r),await j.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(Jc,"sendLogs");var ap=s(n=>async e=>{e.length!==0&&await Jc(n,e)},"dispatchFunction"),Jr,nr=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jr||(Jr=new ie("unified-log-transport",1,ap(e)))}log(e,t){Jr.enqueue(e),t.waitUntil(Jr.waitUntilFlushed())}};var Ai=class extends Re{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new rr(this.options)}},cp="https://logging.googleapis.com/v2/entries:write?alt=json",_i={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},rr=class{static{s(this,"GoogleLogTransport")}constructor(e){g("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Le.init(this.#e)}log(e,t){if(!this.#t)throw new ae("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:nt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_i[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=ln(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length===0)return;this.#t||(this.#t=await Le.init(this.#e));let t=await Be({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await j.fetch(cp,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await se({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("google-log-transport",1,this.dispatchFunction)};var Kr="gcp";function Qr(n){let e={allMessages:nt(n.messages)},t="zuplo-production",r=ln(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:_i[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(Qr,"gcpLogFormat");var or=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level](Qr(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:nt(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var Mi=class extends Re{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ir(this.options)}},ki="__ddtags",Li="__ddattr",Ni=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),up=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ni(r)):t.push(`${Ni(r)}:${Ni(o.toString())}`)}),t.join(",")},"formatTags"),ir=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},i=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[ki];l&&typeof l=="object"&&(g("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[ki]!==void 0);d>-1&&(Object.assign(r,i[d][ki]),i.splice(d,1));let p=t.custom[Li];p&&typeof p=="object"&&(g("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[Li]!==void 0);m>-1&&(Object.assign(o,i[m][Li]),i.splice(m,1))}let a=nt(i),c={...e,activityId:e.requestId,trace:e.requestId},u=Object.assign({message:{...c,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ln(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:up(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(u),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await se({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("data-dog-transport",10,this.dispatchFunction)};var sr=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Qr(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Di=Ce("zuplo:logging"),Yr=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Di("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Lr);return i?o.push(new sr(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new nr(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new er(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Di("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Lr);if(a&&a.captureUserLogs===!0?r.push(new sr(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new nr(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new rr({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){g("logging.datadog.legacy-initialization");let c=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ir({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return at.forEach(c=>{c instanceof Re&&r.push(c.getTransport())}),await Promise.all(r.map(async c=>{c.init&&await c.init()})),new er(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i,a){Di("Gateway.createRequestLoggers");let c=new Vr(r,o,i,a),u=new tr(e,t,this.systemCoreLogger,c);return{userRequestLogger:new tr(e,t,this.userCoreLogger,c),systemRequestLogger:u}}};var pn=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Xr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}};var Zi=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new ae(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},eo=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof xt||e instanceof xe))throw new ae("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new Zi(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Xr(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new f(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let i=o.urlPattern.exec({pathname:e});if(i!==null)return new pn(o.config,o.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],i=o.urlPattern.exec({pathname:e});if(i!==null){let a=new pn(o.config,o.executableHandler,i.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as lp}from"node:async_hooks";var to={context:new lp};var qi;function Kc(n){qi=n}s(Kc,"setGlobalZuploEventContext");function It(){if(qi===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return qi}s(It,"getGlobalZuploEventContext");function Qc({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ac.includes(o.toLowerCase())&&!cc.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qa)}else sc.forEach(r=>{t.delete(r)});return t}s(Qc,"normalizeIncomingRequestHeaders");var Et=Ce("zuplo:runtime"),Ie=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Et("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Et("Gateway.initialize"),!n.#e){let i=await Yr.init(r),a=await e(),c={...a,corsPolicies:Ec(a.corsPolicies)},u=new n(c,t,i,o);n.#e=u}if(!n.#e)throw new ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Et("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new ae("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Br,jr,ke];setupRoutes=s(()=>{Et("Gateway.setupRoutes");let e=this.routeData,t=new eo;if(e.routes.length===0)return li(t,this),bi(t,this),yi(t,this),Tc(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(Uc(t,this),$c(t,this)),li(t,this),bi(t,this),yi(t,this);for(let i of at)i instanceof Ee&&i.registerRoutes(t,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let c=new Te({processors:this.#r,handler:a,gateway:this}),u=new xt(i);t.addRoute(u,c.execute)}),Sc(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Et("Gateway.internalErrorResponse"),t.log.error(r,o);let i={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)i=o.extensionMembers;else if(o.cause){let a=qt(o.cause);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}else{let a=qt(o);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}return T.internalServerError(e,t,{detail:o.message,...i})}async handleRequest(e,t,r){let o=e.headers.get(an)??e.headers.get(Ka)??r?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mt);Kc(t);let a=Qc({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(an,o);let c=new Request(e,{headers:a});if(["GET","HEAD"].includes(c.method)&&c.body){let B=new Headers(c.headers);B.set(Vo,"true"),c=new Request(c,{headers:B,body:null})}c=await hc(c);let u=new URL(c.url),l=u.pathname,d=this.#n.lookup(l,c.method);if(!d)throw new ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,i,t,p,c,d.routeConfiguration);cn(u)||m.debug(`Request received '${u.pathname}'`,{method:c.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let x=new no(e.headers),b=new ue(c,{params:d.params}),P=new ro({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:x,parentContext:r?.parentContext}),N=to.context.getStore();N&&(N.context=P);let A=d.routeConfiguration.raw();dp.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[lt.RoutePathPattern]:P.route.pathPattern,[lt.RouteOperationId]:A.operationId,[lt.RouteTrace]:A["x-zuplo-trace"],[lt.RouteSystem]:cn(u)?!0:void 0}),_e.initialize(P,b);try{if(ne.addLogger(P,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!cn(u):!u.pathname.startsWith("/__zuplo")){let O=await mc(b,P);if(O instanceof Response)return O;{let F=_e.getContextExtensions(P);b=O,F.latestRequest=b}}let B=d.executableHandler;pp(B,d,c),Et("Gateway.handleRequest - call user handler");let $=await B(b,P);if(Et("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let G;if($.headers.get(an)===null&&!$.webSocket){let O=new Headers($.headers);O.set(an,o),G=new Response($.body,{status:$.status,statusText:$.statusText,headers:O,cf:$.cf})}else G=$;return G}catch(B){return B instanceof k?(m.error(B),h.warn(B)):h.error(B),await this.errorHandler(b,P,"Error executing handler",B)}}};function pp(n,e,t){if(Et("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(pp,"checkHandler");import{SpanStatusCode as Yc,trace as Xc}from"@opentelemetry/api";var eu=s(async(n,e,t)=>{let r=Ie.instance.routeData.policies,o=Yn([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let i=o[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,t);if(l instanceof Request||l instanceof ue||l instanceof Response)return l instanceof Response||l instanceof ue?l:new ue(l);{let d=new f(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Yc.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),tu=s(async(n,e,t,r)=>{let o=Ie.instance.routeData.policies,i=Xn([n],o);if(i.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=i[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new f(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Yc.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function mp(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[i,a]=o.split("=");i&&a&&(r[i.trim()]=a.trim())}),r.asnum&&(e[Un]=r.asnum),r.zip&&(e[Hn]=r.zip.split("+")[0]),r.dma&&(e[Fn]=r.dma),r.region_code&&(e[jn]=r.region_code),r.timezone&&(e[zn]=r.timezone),r.city&&(e[Cr]=r.city),r.continent&&(e[Or]=r.continent),r.country_code&&(e[Ar]=r.country_code),r.long&&(e[_r]=r.long),r.lat&&(e[kr]=r.lat),e}catch{return{}}}s(mp,"parseEdgeScapeHeader");function nu(n,e){let t=mp(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}s(nu,"setZpHeadersFromAkamaiEdgeScapeHeader");var no=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(ni);if(t){let r=new Headers(e);nu(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Un);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Xo)??void 0}get city(){return this.#e.get(Wo)??this.#e.get(Cr)??void 0}get continent(){return this.#e.get(Jo)??this.#e.get(Or)??void 0}get country(){return this.#e.get(Ko)??this.#e.get(Ar)??void 0}get latitude(){return this.#e.get(Yo)??this.#e.get(kr)??void 0}get longitude(){return this.#e.get(Qo)??this.#e.get(_r)??void 0}get colo(){return this.#e.get(ei)??void 0}get postalCode(){return this.#e.get(tc)??this.#e.get(Hn)??void 0}get metroCode(){return this.#e.get(ec)??this.#e.get(Fn)??void 0}get region(){return this.#e.get(Ya)??this.#e.get(ti)??void 0}get regionCode(){return this.#e.get(Xa)??this.#e.get(jn)??void 0}get timezone(){return this.#e.get(nc)??this.#e.get(zn)??void 0}get httpProtocol(){return this.#e.get(ic)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function Tt(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}s(Tt,"createRewriteContext");var Jn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Kn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},_e=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=s(async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o},"onResponseSending");onHandlerResponse=s(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},ro=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=o,this.invokeInboundPolicy=(u,l)=>eu(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>tu(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new ue(d,l);return Ie.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{_e.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{_e.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fp="Error initializing gateway. Check your configuration for errors or contact support.",gp="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",$i=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=s(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await yc(this.runtimeInit)}catch(i){this.handleError(i,gp,e)}return dc(s(async(i,a)=>{let c;try{c=await Ie.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,fp,i)}let u={context:void 0};return to.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function hp(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var c=1,u="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){u+=n[i++]+n[i++];continue}if(n[i]===")"){if(c--,c===0){i++;break}}else if(n[i]==="("&&(c++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));u+=n[i++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(t));if(!u)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:u}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(hp,"lexer");function Hi(n,e){e===void 0&&(e={});for(var t=hp(n),r=e.prefixes,o=r===void 0?"./":r,i=e.delimiter,a=i===void 0?"/#?":i,c=[],u=0,l=0,d="",p=s(function(V){if(l<t.length&&t[l].type===V)return t[l++].value},"tryConsume"),m=s(function(V){var S=p(V);if(S!==void 0)return S;var E=t[l],U=E.type,we=E.index;throw new TypeError("Unexpected ".concat(U," at ").concat(we,", expected ").concat(V))},"mustConsume"),h=s(function(){for(var V="",S;S=p("CHAR")||p("ESCAPED_CHAR");)V+=S;return V},"consumeText"),x=s(function(V){for(var S=0,E=a;S<E.length;S++){var U=E[S];if(V.indexOf(U)>-1)return!0}return!1},"isSafe"),b=s(function(V){var S=c[c.length-1],E=V||(S&&typeof S=="string"?S:"");if(S&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(S.name,'"'));return!E||x(E)?"[^".concat(Ui(a),"]+?"):"(?:(?!".concat(Ui(E),")[^").concat(Ui(a),"])+?")},"safePattern");l<t.length;){var P=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var B=P||"";o.indexOf(B)===-1&&(d+=B,B=""),d&&(c.push(d),d=""),c.push({name:N||u++,prefix:B,suffix:"",pattern:A||b(B),modifier:p("MODIFIER")||""});continue}var $=P||p("ESCAPED_CHAR");if($){d+=$;continue}d&&(c.push(d),d="");var G=p("OPEN");if(G){var B=h(),O=p("NAME")||"",F=p("PATTERN")||"",Y=h();m("CLOSE"),c.push({name:O||(F?u++:""),pattern:O&&!F?b(B):F,prefix:B,suffix:Y,modifier:p("MODIFIER")||""});continue}m("END")}return c}s(Hi,"parse");function ru(n,e){return yp(Hi(n,e),e)}s(ru,"compile");function yp(n,e){e===void 0&&(e={});var t=bp(e),r=e.encode,o=r===void 0?function(u){return u}:r,i=e.validate,a=i===void 0?!0:i,c=n.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),t)});return function(u){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",x=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!x)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var P=o(m[b],p);if(a&&!c[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var P=o(String(m),p);if(a&&!c[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!h){var N=x?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(yp,"tokensToFunction");function Ui(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Ui,"escapeString");function bp(n){return n&&n.sensitive?"":"i"}s(bp,"flags");var wp=Ce("zuplo:runtime"),ji=new TextEncoder,ou={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Rp=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],mn=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,t){let r=new zi(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){wp("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=j.fetch(o,i);if(r===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},zi=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:x,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=c;let P,N;(!u||!l)&&([P,N]=vp(this.url,this.headers)),this.service=u||P||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter($=>x||!Rp.includes($)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map($=>$+":"+($==="host"?this.url.host:(this.headers.get($)||"").replace(/\s+/g," "))).join(`
66
66
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=su(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([$])=>{if(!$)return!1;if(this.service==="s3"){if(B.has($))return!1;B.add($)}return!0}).map($=>$.map(G=>su(encodeURIComponent(G)))).sort(([$,G],[O,F])=>$<O?-1:$>O?1:G<F?-1:G>F?1:0).map($=>$.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await ar("AWS4"+this.secretAccessKey,e),i=await ar(o,this.region),a=await ar(i,this.service);r=await ar(a,"aws4_request"),this.cache.set(t,r)}return Fi(await ar(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fi(await iu(await this.canonicalString()))].join(`
67
67
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
68
68
  `,this.signedHeaders,await this.hexBodyHash()].join(`
@@ -6132,7 +6132,10 @@ export declare interface ZuploContext extends EventTarget {
6132
6132
  readonly invokeInboundPolicy: (policyName: string, request: ZuploRequest) => Promise<Response | ZuploRequest>;
6133
6133
  readonly invokeOutboundPolicy: (policyName: string, response: Response, request: ZuploRequest) => Promise<Response>;
6134
6134
  /**
6135
- * Invokes a route based on a Request without going back out to HTTP
6135
+ * Invokes a route based on a Request without going back out to HTTP.
6136
+ * Can take a relative route path to invoke on the Gateway
6137
+ * Example: "/my/route" will invoke http://localhost/my/route on the Gateway
6138
+ * without having to rebuild the Request's protocol and host.
6136
6139
  * @beta
6137
6140
  */
6138
6141
  readonly invokeRoute: <TOptions extends RequestGeneric = RequestGeneric>(input: string | URL | Request, init?: ZuploRequestInit<TOptions>) => Promise<Response>;
@@ -1098,7 +1098,10 @@ declare interface ZuploContext extends EventTarget {
1098
1098
  readonly invokeInboundPolicy: (policyName: string, request: ZuploRequest) => Promise<Response | ZuploRequest>;
1099
1099
  readonly invokeOutboundPolicy: (policyName: string, response: Response, request: ZuploRequest) => Promise<Response>;
1100
1100
  /**
1101
- * Invokes a route based on a Request without going back out to HTTP
1101
+ * Invokes a route based on a Request without going back out to HTTP.
1102
+ * Can take a relative route path to invoke on the Gateway
1103
+ * Example: "/my/route" will invoke http://localhost/my/route on the Gateway
1104
+ * without having to rebuild the Request's protocol and host.
1102
1105
  * @beta
1103
1106
  */
1104
1107
  readonly invokeRoute: <TOptions extends RequestGeneric = RequestGeneric>(input: string | URL | Request, init?: ZuploRequestInit<TOptions>) => Promise<Response>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.51.12",
4
+ "version": "6.51.14",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {