@zuplo/runtime 5.2071.0 → 5.2073.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.min.cjs CHANGED
@@ -59,7 +59,7 @@
59
59
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
60
60
  `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||cs(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 g="["+p.newline+a.map((I,y)=>{let T=a.length-1===y?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,y,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if(ze(a)){let g=ls(a);if(u.filter&&(g=g.filter(y=>u.filter?.(a,y))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((y,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof y=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(y),S=h||P?y:s(y,u,"",l+1),H=s(a[y],u,c+d,l+1);return u.transform&&(H=u.transform(a,y,H)),p.indent+String(S)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
61
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(dn,"stringifyObject");function Ue(n){return n.map(e=>se(e))}i(Ue,"makeErrorsSerializable");function st(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:Oe(se(e))}i(st,"extractBestMessage");function Ss(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ot(t))if(t.stack)e.push(t.stack);else{let r=dn(se(t));e.push(r)}else if(typeof t=="object"){let r=dn(t);e.push(r)}else{let r=io(t);e.push(r)}}),e.join(`
62
- `)}i(Ss,"messagesToMultilineText");function Oe(n){return typeof n=="string"?n:JSON.stringify(n)}i(Oe,"stringifyNonString");function io(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"?zr(n):"unknown"}i(io,"stringifyNonStringToText");var pn=require("jose");async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}i(ae,"fetchRetry");async function Ee({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new pn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ee,"getTokenFromGcpServiceAccount");async function Os(n,e,t){return Cs(n,{token:e,returnSecureToken:!0},t)}i(Os,"exchangeFirebaseJwtForIdToken");async function mn(n,e,t){return Cs(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(mn,"exchangeGgpJwtForIdToken");async function Cs(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Cs,"fetchToken");var le=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,pn.importPKCS8)(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 gn=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Lt(this.options)}},Ol="https://logging.googleapis.com/v2/entries:write?alt=json",so={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Lt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await le.init(this.#e)}log(e,t){if(!this.#t)throw new F("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ue(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:so[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=st(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await le.init(this.#e));let t=await Ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Ol,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new $("google-log-transport",1,this.dispatchFunction)};var fn="gcp";function hn(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:so[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(hn,"gcpLogFormat");var Nt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var yn=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new kt(this.options)}},ao="__ddtags",uo="__ddattr",co=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Cl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(co(r)):t.push(`${co(r)}:${co(o.toString())}`)}),t.join(",")},"formatTags"),kt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[ao];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[ao]!==void 0);a>-1&&(Object.assign(r,s[a][ao]),s.splice(a,1));let u={},c=t.custom[uo];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[uo]!==void 0);l>-1&&(Object.assign(u,s[l][uo]),s.splice(l,1));let d=Ue(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Cl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var Mt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(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 Al=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ue(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),bn,wn=class{static{i(this,"RemoteLogTransport")}constructor(e){bn||(bn=new $("remote-log-transport",1,Al(e)))}log(e,t){bn.enqueue(e),t.waitUntil(bn.waitUntilFlushed())}};var _l={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},As=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:_l[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ll=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=As(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Rn,Pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Rn||(Rn=new $("unified-log-transport",1,Ll(e)))}async log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var lo=(0,_s.debug)("zuplo:logging"),En=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;lo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Tt);return s?o.push(new Mt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Pn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new At(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){lo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Tt);if(a&&a.captureUserLogs===!0?r.push(new Mt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new wn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Lt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new At(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){lo("Gateway.createRequestLoggers");let a=new ln(r,o,s),u=new _t(e,t,this.systemCoreLogger,a);return{userRequestLogger:new _t(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var po=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},at=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},mo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},ut=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof We||e instanceof K))throw new F("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new po(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new mo(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new at(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new at(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var go;function Ls(n){go=n}i(Ls,"setGlobalZuploEventContext");function In(){if(go===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return go}i(In,"getGlobalZuploEventContext");function Ns({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Qi.includes(o.toLowerCase())&&!Xi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Zi)}else Yi.forEach(r=>{t.delete(r)});return t}i(Ns,"normalizeIncomingRequestHeaders");var Ie=(0,ks.debug)("zuplo:runtime"),Nl=i(n=>{let e=n.findIndex(t=>t.name===St.name);return e>-1?[...n.splice(e),St]:[...n,St]},"setupSystemNoVersion"),ne=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ie("Gateway.constructor"),me,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ie("Gateway.initialize"),n.#e||await fo.trace.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[me.SystemTrace]:!0}},async a=>{try{let u=await En.init(r),c=e(),l={...c,corsPolicies:gs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new F("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ie("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new F("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[cn,an,oe];#o;setupRoutes=()=>{Ie("Gateway.setupRoutes");let e=this.routeData,t=Nl(e.versions),r=new ut(t);if(e.routes.length===0)return Br(r,this),Yr(r,this),Jr(r,this),fs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ts(r,this),Is(r,this)),Br(r,this),Yr(r,this),Jr(r,this);for(let s of ve)s instanceof xe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new We(s);r.addRoute(c,u.execute)}),hs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new b("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ie("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ie("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=se(r.cause);"stack"in s&&(s.stack=vs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;Ls(r);let a=Ns({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Be,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(vr,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new F(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new Tn(e.headers),y=new z(u,{params:g.params}),T=new xn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();fo.trace.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[me.RoutePathPattern]:T.route.pathPattern,[me.RouteOperationId]:_.operationId,[me.RouteTrace]:_["x-zuplo-trace"],[me.RouteSystem]:et(p)?!0:void 0});let h=re.initialize(T,y);if(g.routeConfiguration===Kr&&vt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof We)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!et(p):!p.pathname.startsWith("/__zuplo")){let f=await os(y,T);if(f instanceof Response)return f;{let w=re.getContextExtensions(T);y=f,w.latestRequest=y}}et(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;kl(P,g,u),Ie("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ie("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(Be)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(Be,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ie("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function kl(n,e,t){if(Ie("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(kl,"checkHandler");var Ms=i(async(n,e,t)=>{let r=ne.instance.routeData.policies,o=Ct([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Tn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Lr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Nr)??void 0}get city(){return this.#e.get(Sr)??this.#e.get(zi)??void 0}get continent(){return this.#e.get(Or)??this.#e.get(Vi)??void 0}get country(){return this.#e.get(Cr)??this.#e.get(Gi)??void 0}get latitude(){return this.#e.get(_r)??this.#e.get(Ji)??void 0}get longitude(){return this.#e.get(Ar)??this.#e.get(Wi)??void 0}get colo(){return this.#e.get(kr)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(Mr)??void 0}get metroCode(){return this.#e.get(Fi)??this.#e.get(Dr)??void 0}get region(){return this.#e.get(qi)??this.#e.get(Ur)??void 0}get regionCode(){return this.#e.get($i)??this.#e.get(Hr)??void 0}get timezone(){return this.#e.get(ji)??this.#e.get(Zr)??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}}},tt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},nt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},xn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ms(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ge=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)}};var Ml=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Dl(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Ml.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Dl,"isRestrictedEnvVariableName");function Ul(n){return!!n.startsWith("ZUPLO_")}i(Ul,"isZuploReadableEnvVariableName");var ie=new Proxy({},{get(n,e){if(!(Dl(String(e))&&!Ul(String(e))))return R.instance.runtime[String(e)]}});var Ds=require("node:async_hooks");var Us={request:new Ds.AsyncLocalStorage};var Hl="Error initializing gateway. Check your configuration for errors or contact support.",Zl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",vn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(Be)??e.headers.get(Hi)??crypto.randomUUID(),s=e.headers.get(je),a={requestId:o,rayId:s};return Us.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await as(this.runtimeInit)}catch(c){this.handleError(c,Zl,e)}return ns(i(async(c,l)=>{let d;try{d=await ne.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Hl,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Vs=Ce(Le());function ql(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(ql,"lexer");function ho(n,e){e===void 0&&(e={});for(var t=ql(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Fl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ho,"parse");function Hs(n,e){return $l(ho(n,e),e)}i(Hs,"compile");function $l(n,e){e===void 0&&(e={});var t=Bl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i($l,"tokensToFunction");function Fl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Fl,"escapeString");function Bl(n){return n&&n.sensitive?"":"i"}i(Bl,"flags");var Fs=Ce(Le());var jl=(0,Fs.debug)("zuplo:runtime"),bo=new TextEncoder,Zs={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"},zl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ct=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new wo(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){jl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}},wo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Vl(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!zl.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
62
+ `)}i(Ss,"messagesToMultilineText");function Oe(n){return typeof n=="string"?n:JSON.stringify(n)}i(Oe,"stringifyNonString");function io(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"?zr(n):"unknown"}i(io,"stringifyNonStringToText");var pn=require("jose");async function ae(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}i(ae,"fetchRetry");async function Ee({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new pn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ee,"getTokenFromGcpServiceAccount");async function Os(n,e,t){return Cs(n,{token:e,returnSecureToken:!0},t)}i(Os,"exchangeFirebaseJwtForIdToken");async function mn(n,e,t){return Cs(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(mn,"exchangeGgpJwtForIdToken");async function Cs(n,e,t){let r=await ae(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Cs,"fetchToken");var le=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,pn.importPKCS8)(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 gn=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Lt(this.options)}},Ol="https://logging.googleapis.com/v2/entries:write?alt=json",so={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Lt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await le.init(this.#e)}log(e,t){if(!this.#t)throw new F("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ue(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:so[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=st(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await le.init(this.#e));let t=await Ee({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Ol,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new $("google-log-transport",1,this.dispatchFunction)};var fn="gcp";function hn(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:so[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(hn,"gcpLogFormat");var Nt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e.log(JSON.stringify(e))}};var yn=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new kt(this.options)}},ao="__ddtags",uo="__ddattr",co=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Cl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(co(r)):t.push(`${co(r)}:${co(o.toString())}`)}),t.join(",")},"formatTags"),kt=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[ao];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[ao]!==void 0);a>-1&&(Object.assign(r,s[a][ao]),s.splice(a,1));let u={},c=t.custom[uo];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[uo]!==void 0);l>-1&&(Object.assign(u,s[l][uo]),s.splice(l,1));let d=Ue(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Cl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new $("data-dog-transport",10,this.dispatchFunction)};var Mt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(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 Al=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ue(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),bn,wn=class{static{i(this,"RemoteLogTransport")}constructor(e){bn||(bn=new $("remote-log-transport",1,Al(e)))}log(e,t){bn.enqueue(e),t.waitUntil(bn.waitUntilFlushed())}};var _l={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},As=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:_l[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ll=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=As(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Rn,Pn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Rn||(Rn=new $("unified-log-transport",1,Ll(e)))}async log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var lo=(0,_s.debug)("zuplo:logging"),En=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;lo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Tt);return s?o.push(new Mt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Pn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new At(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){lo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Tt);if(a&&a.captureUserLogs===!0?r.push(new Mt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new wn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Lt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ve.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new At(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){lo("Gateway.createRequestLoggers");let a=new ln(r,o,s),u=new _t(e,t,this.systemCoreLogger,a);return{userRequestLogger:new _t(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var po=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},at=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},mo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},ut=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof We||e instanceof K))throw new F("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new po(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new mo(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new at(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new at(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var go;function Ls(n){go=n}i(Ls,"setGlobalZuploEventContext");function In(){if(go===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return go}i(In,"getGlobalZuploEventContext");function Ns({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Qi.includes(o.toLowerCase())&&!Xi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Zi)}else Yi.forEach(r=>{t.delete(r)});return t}i(Ns,"normalizeIncomingRequestHeaders");var Ie=(0,ks.debug)("zuplo:runtime"),Nl=i(n=>{let e=n.findIndex(t=>t.name===St.name);return e>-1?[...n.splice(e),St]:[...n,St]},"setupSystemNoVersion"),ne=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ie("Gateway.constructor"),me,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ie("Gateway.initialize"),n.#e||await fo.trace.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[me.SystemTrace]:!0}},async a=>{try{let u=await En.init(r),c=e(),l={...c,corsPolicies:gs(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new F("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ie("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new F("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[cn,an,oe];#o;setupRoutes=()=>{Ie("Gateway.setupRoutes");let e=this.routeData,t=Nl(e.versions),r=new ut(t);if(e.routes.length===0)return Br(r,this),Yr(r,this),Jr(r,this),fs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ts(r,this),Is(r,this)),Br(r,this),Yr(r,this),Jr(r,this);for(let s of ve)s instanceof xe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new We(s);r.addRoute(c,u.execute)}),hs(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new b("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ie("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ie("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=se(r.cause);"stack"in s&&(s.stack=vs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;Ls(r);let a=Ns({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Be,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(vr,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new F(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new Tn(e.headers),y=new z(u,{params:g.params}),T=new xn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();fo.trace.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[me.RoutePathPattern]:T.route.pathPattern,[me.RouteOperationId]:_.operationId,[me.RouteTrace]:_["x-zuplo-trace"],[me.RouteSystem]:et(p)?!0:void 0});let h=re.initialize(T,y);if(g.routeConfiguration===Kr&&vt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof We)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!et(p):!p.pathname.startsWith("/__zuplo")){let f=await os(y,T);if(f instanceof Response)return f;{let w=re.getContextExtensions(T);y=f,w.latestRequest=y}}et(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;kl(P,g,u),Ie("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ie("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(Be)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(Be,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ie("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function kl(n,e,t){if(Ie("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(kl,"checkHandler");var Ms=i(async(n,e,t)=>{let r=ne.instance.routeData.policies,o=Ct([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Tn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Lr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Nr)??void 0}get city(){return this.#e.get(Sr)??this.#e.get(zi)??void 0}get continent(){return this.#e.get(Or)??this.#e.get(Vi)??void 0}get country(){return this.#e.get(Cr)??this.#e.get(Gi)??void 0}get latitude(){return this.#e.get(_r)??this.#e.get(Ji)??void 0}get longitude(){return this.#e.get(Ar)??this.#e.get(Wi)??void 0}get colo(){return this.#e.get(kr)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(Mr)??void 0}get metroCode(){return this.#e.get(Fi)??this.#e.get(Dr)??void 0}get region(){return this.#e.get(qi)??this.#e.get(Ur)??void 0}get regionCode(){return this.#e.get($i)??this.#e.get(Hr)??void 0}get timezone(){return this.#e.get(ji)??this.#e.get(Zr)??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}}},tt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},nt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},re=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},xn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ms(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{re.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{re.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ge=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)}};var Ml=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Dl(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Ml.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Dl,"isRestrictedEnvVariableName");function Ul(n){return!!n.startsWith("ZUPLO_")}i(Ul,"isZuploReadableEnvVariableName");var ie=new Proxy({},{get(n,e){if(!(Dl(String(e))&&!Ul(String(e))))return R.instance.runtime[String(e)]}});var Ds=require("node:async_hooks");var Us={request:new Ds.AsyncLocalStorage};var Hl="Error initializing gateway. Check your configuration for errors or contact support.",Zl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",vn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(Be)??e.headers.get(Hi)??crypto.randomUUID(),s=e.headers.get(je),a={requestId:o,rayId:s};return Us.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await as(this.runtimeInit)}catch(c){this.handleError(c,Zl,e)}return ns(i(async(c,l)=>{let d;try{d=await ne.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Hl,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Vs=Ce(Le());function ql(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(ql,"lexer");function ho(n,e){e===void 0&&(e={});for(var t=ql(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Fl(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ho,"parse");function Hs(n,e){return $l(ho(n,e),e)}i(Hs,"compile");function $l(n,e){e===void 0&&(e={});var t=Bl(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i($l,"tokensToFunction");function Fl(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Fl,"escapeString");function Bl(n){return n&&n.sensitive?"":"i"}i(Bl,"flags");var Fs=Ce(Le());var jl=(0,Fs.debug)("zuplo:runtime"),bo=new TextEncoder,Zs={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"},zl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ct=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new wo(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){jl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}},wo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Vl(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!zl.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
63
63
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.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,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=$s(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>$s(encodeURIComponent(H)))).sort(([S,H],[f,w])=>S<f?-1:S>f?1:H<w?-1:H>w?1:0).map(S=>S.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 Dt("AWS4"+this.secretAccessKey,e),s=await Dt(o,this.region),a=await Dt(s,this.service);r=await Dt(a,"aws4_request"),this.cache.set(t,r)}return yo(await Dt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,yo(await qs(await this.canonicalString()))].join(`
64
64
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
65
65
  `,this.signedHeaders,await this.hexBodyHash()].join(`
package/index.min.js CHANGED
@@ -59,7 +59,7 @@ var ka=Object.create;var Mn=Object.defineProperty;var Ma=Object.getOwnPropertyDe
59
59
  `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=i(g=>{if(u.inlineCharacterLimit===void 0)return g;let I=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
60
60
  `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ts(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 g="["+p.newline+a.map((I,y)=>{let T=a.length-1===y?p.newline:","+p.newlineOrSpace,_=s(I,u,c+d,l+1);return u.transform&&(_=u.transform(a,y,_)),p.indent+_+T}).join("")+p.pad+"]";return r.pop(),m(g)}if(Be(a)){let g=ns(a);if(u.filter&&(g=g.filter(y=>u.filter?.(a,y))),g.length===0)return"{}";r.push(a);let I="{"+p.newline+g.map((y,T)=>{let _=g.length-1===T?p.newline:","+p.newlineOrSpace,h=typeof y=="symbol",P=!h&&/^[a-z$_][$\w]*$/i.test(y),S=h||P?y:s(y,u,"",l+1),H=s(a[y],u,c+d,l+1);return u.transform&&(H=u.transform(a,y,H)),p.indent+String(S)+": "+H+_}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
61
61
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(tn,"stringifyObject");function Me(n){return n.map(e=>ie(e))}i(Me,"makeErrorsSerializable");function et(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:Se(ie(e))}i(et,"extractBestMessage");function Ps(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Pt(t))if(t.stack)e.push(t.stack);else{let r=tn(ie(t));e.push(r)}else if(typeof t=="object"){let r=tn(t);e.push(r)}else{let r=Nr(t);e.push(r)}}),e.join(`
62
- `)}i(Ps,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}i(Se,"stringifyNonString");function Nr(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"?wr(n):"unknown"}i(Nr,"stringifyNonStringToText");import{importPKCS8 as Sc,SignJWT as Oc}from"jose";async function se(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}i(se,"fetchRetry");async function Pe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Oc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Pe,"getTokenFromGcpServiceAccount");async function Es(n,e,t){return Is(n,{token:e,returnSecureToken:!0},t)}i(Es,"exchangeFirebaseJwtForIdToken");async function nn(n,e,t){return Is(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(nn,"exchangeGgpJwtForIdToken");async function Is(n,e,t){let r=await se(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Is,"fetchToken");var le=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Sc(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 kr=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new xt(this.options)}},Cc="https://logging.googleapis.com/v2/entries:write?alt=json",Mr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},xt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await le.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Mr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=et(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await le.init(this.#e));let t=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Cc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(n){let e={allMessages:Me(n.messages)},t="zuplo-production",r=et(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Mr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(on,"gcpLogFormat");var vt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Zr=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new St(this.options)}},Dr="__ddtags",Ur="__ddattr",Hr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ac=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Hr(r)):t.push(`${Hr(r)}:${Hr(o.toString())}`)}),t.join(",")},"formatTags"),St=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Dr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Dr]!==void 0);a>-1&&(Object.assign(r,s[a][Dr]),s.splice(a,1));let u={},c=t.custom[Ur];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Ur]!==void 0);l>-1&&(Object.assign(u,s[l][Ur]),s.splice(l,1));let d=Me(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:et(d),service:e.loggingId,ddtags:Ac(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var Ot=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(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 _c=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{i(this,"RemoteLogTransport")}constructor(e){sn||(sn=new F("remote-log-transport",1,_c(e)))}log(e,t){sn.enqueue(e),t.waitUntil(sn.waitUntilFlushed())}};var Lc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ts=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Lc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Nc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ts(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{i(this,"UnifiedLogTransport")}constructor(e){un||(un=new F("unified-log-transport",1,Nc(e)))}async log(e,t){un.enqueue(e),t.waitUntil(un.waitUntilFlushed())}};var qr=(0,xs.debug)("zuplo:logging"),ln=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;qr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(jt);return s?o.push(new Ot(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new vt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new cn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new It(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){qr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(jt);if(a&&a.captureUserLogs===!0?r.push(new Ot(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new vt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new an({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new St({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return xe.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new It(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){qr("Gateway.createRequestLoggers");let a=new en(r,o,s),u=new Tt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Tt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ve=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var $r=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ct=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fr=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},At=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ve||e instanceof K))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new $r(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Fr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Ct(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ct(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Br;function vs(n){Br=n}i(vs,"setGlobalZuploEventContext");function dn(){if(Br===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Br}i(dn,"getGlobalZuploEventContext");function Ss({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ji.includes(o.toLowerCase())&&!zi.includes(r.toLowerCase())&&t.delete(r)}t.delete(_i)}else Bi.forEach(r=>{t.delete(r)});return t}i(Ss,"normalizeIncomingRequestHeaders");var Ee=(0,Cs.debug)("zuplo:runtime"),kc=i(n=>{let e=n.findIndex(t=>t.name===Rt.name);return e>-1?[...n.splice(e),Rt]:[...n,Rt]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ee("Gateway.constructor"),ge,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ee("Gateway.initialize"),n.#e||await Os.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[ge.SystemTrace]:!0}},async a=>{try{let u=await ln.init(r),c=e(),l={...c,corsPolicies:ss(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Xt,Yt,re];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,t=kc(e.versions),r=new At(t);if(e.routes.length===0)return fr(r,this),xr(r,this),Ir(r,this),as(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(bs(r,this),ys(r,this)),fr(r,this),xr(r,this),Ir(r,this);for(let s of xe)s instanceof Te&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new Ve(s);r.addRoute(c,u.execute)}),us(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new b("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ee("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ee("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=ie(r.cause);"stack"in s&&(s.stack=Rs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;vs(r);let a=Ss({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Wn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new pn(e.headers),y=new z(u,{params:g.params}),T=new mn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Os.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[ge.RoutePathPattern]:T.route.pathPattern,[ge.RouteOperationId]:_.operationId,[ge.RouteTrace]:_["x-zuplo-trace"],[ge.RouteSystem]:Ye(p)?!0:void 0});let h=ne.initialize(T,y);if(g.routeConfiguration===Tr&&yt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ve)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Ye(p):!p.pathname.startsWith("/__zuplo")){let f=await Ki(y,T);if(f instanceof Response)return f;{let w=ne.getContextExtensions(T);y=f,w.latestRequest=y}}Ye(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Mc(P,g,u),Ee("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ee("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(qe)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(qe,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function Mc(n,e,t){if(Ee("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Mc,"checkHandler");var As=i(async(n,e,t)=>{let r=te.instance.routeData.policies,o=Et([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var pn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(er);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(tr)??void 0}get city(){return this.#e.get(Jn)??this.#e.get(Ui)??void 0}get continent(){return this.#e.get(Kn)??this.#e.get(Hi)??void 0}get country(){return this.#e.get(Yn)??this.#e.get(Zi)??void 0}get latitude(){return this.#e.get(Xn)??this.#e.get($i)??void 0}get longitude(){return this.#e.get(Qn)??this.#e.get(qi)??void 0}get colo(){return this.#e.get(nr)??void 0}get postalCode(){return this.#e.get(Mi)??this.#e.get(rr)??void 0}get metroCode(){return this.#e.get(ki)??this.#e.get(or)??void 0}get region(){return this.#e.get(Li)??this.#e.get(ir)??void 0}get regionCode(){return this.#e.get(Ni)??this.#e.get(sr)??void 0}get timezone(){return this.#e.get(Di)??this.#e.get(ar)??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}}},bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},wt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>As(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fe=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)}};var Dc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Uc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Dc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Uc,"isRestrictedEnvVariableName");function Hc(n){return!!n.startsWith("ZUPLO_")}i(Hc,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(n,e){if(!(Uc(String(e))&&!Hc(String(e))))return R.instance.runtime[String(e)]}});import{AsyncLocalStorage as Zc}from"node:async_hooks";var _s={request:new Zc};var qc="Error initializing gateway. Check your configuration for errors or contact support.",$c="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",jr=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(qe)??e.headers.get(Ai)??crypto.randomUUID(),s=e.headers.get($e),a={requestId:o,rayId:s};return _s.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await Xi(this.runtimeInit)}catch(c){this.handleError(c,$c,e)}return Wi(i(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,qc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var qs=Oe(_e());function Fc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Fc,"lexer");function zr(n,e){e===void 0&&(e={});for(var t=Fc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(jc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(zr,"parse");function Ls(n,e){return Bc(zr(n,e),e)}i(Ls,"compile");function Bc(n,e){e===void 0&&(e={});var t=zc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(Bc,"tokensToFunction");function jc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(jc,"escapeString");function zc(n){return n&&n.sensitive?"":"i"}i(zc,"flags");var Ds=Oe(_e());var Vc=(0,Ds.debug)("zuplo:runtime"),Gr=new TextEncoder,Ns={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"},Gc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],tt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Wr(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){Vc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}},Wr=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Wc(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!Gc.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
62
+ `)}i(Ps,"messagesToMultilineText");function Se(n){return typeof n=="string"?n:JSON.stringify(n)}i(Se,"stringifyNonString");function Nr(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"?wr(n):"unknown"}i(Nr,"stringifyNonStringToText");import{importPKCS8 as Sc,SignJWT as Oc}from"jose";async function se(n,e,t){for(let r=0;r<=n.retries;r++){let o=M.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}i(se,"fetchRetry");async function Pe({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Oc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Pe,"getTokenFromGcpServiceAccount");async function Es(n,e,t){return Is(n,{token:e,returnSecureToken:!0},t)}i(Es,"exchangeFirebaseJwtForIdToken");async function nn(n,e,t){return Is(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(nn,"exchangeGgpJwtForIdToken");async function Is(n,e,t){let r=await se(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Is,"fetchToken");var le=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Sc(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 kr=class extends X{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new xt(this.options)}},Cc="https://logging.googleapis.com/v2/entries:write?alt=json",Mr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},xt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=R.instance.loggingEnvironmentType,this.#i=R.instance.loggingEnvironmentStage,this.#r=R.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await le.init(this.#e)}log(e,t){if(!this.#t)throw new $("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Me(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Mr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=et(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await le.init(this.#e));let t=await Pe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await M.fetch(Cc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new F("google-log-transport",1,this.dispatchFunction)};var rn="gcp";function on(n){let e={allMessages:Me(n.messages)},t="zuplo-production",r=et(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Mr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(on,"gcpLogFormat");var vt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(e)])}else this.#e.log(JSON.stringify(e))}};var Zr=class extends X{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new St(this.options)}},Dr="__ddtags",Ur="__ddattr",Hr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ac=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Hr(r)):t.push(`${Hr(r)}:${Hr(o.toString())}`)}),t.join(",")},"formatTags"),St=class{static{i(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=R.instance.loggingEnvironmentType,this.#o=R.instance.loggingEnvironmentStage,this.#n=R.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Dr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(g=>g[Dr]!==void 0);a>-1&&(Object.assign(r,s[a][Dr]),s.splice(a,1));let u={},c=t.custom[Ur];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[Ur]!==void 0);l>-1&&(Object.assign(u,s[l][Ur]),s.splice(l,1));let d=Me(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:et(d),service:e.loggingId,ddtags:Ac(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await M.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new F("data-dog-transport",10,this.dispatchFunction)};var Ot=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===rn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[on(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 _c=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await M.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),sn,an=class{static{i(this,"RemoteLogTransport")}constructor(e){sn||(sn=new F("remote-log-transport",1,_c(e)))}log(e,t){sn.enqueue(e),t.waitUntil(sn.waitUntilFlushed())}};var Lc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ts=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Lc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Nc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Ts(t,r);try{await M.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":R.instance.systemUserAgent,"zp-dn":R.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{i(this,"UnifiedLogTransport")}constructor(e){un||(un=new F("unified-log-transport",1,Nc(e)))}async log(e,t){un.enqueue(e),t.waitUntil(un.waitUntilFlushed())}};var qr=(0,xs.debug)("zuplo:logging"),ln=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(R.instance,e),r=await n.setupUserCoreLogger(R.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;qr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(jt);return s?o.push(new Ot(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new vt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new cn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new It(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){qr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(jt);if(a&&a.captureUserLogs===!0?r.push(new Ot(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new vt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new an({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new St({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return xe.forEach(u=>{u instanceof X&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new It(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){qr("Gateway.createRequestLoggers");let a=new en(r,o,s),u=new Tt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Tt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ve=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var $r=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ct=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fr=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},At=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ve||e instanceof K))throw new $("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new $r(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Fr(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new b(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Ct(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ct(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Br;function vs(n){Br=n}i(vs,"setGlobalZuploEventContext");function dn(){if(Br===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Br}i(dn,"getGlobalZuploEventContext");function Ss({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ji.includes(o.toLowerCase())&&!zi.includes(r.toLowerCase())&&t.delete(r)}t.delete(_i)}else Bi.forEach(r=>{t.delete(r)});return t}i(Ss,"normalizeIncomingRequestHeaders");var Ee=(0,Cs.debug)("zuplo:runtime"),kc=i(n=>{let e=n.findIndex(t=>t.name===Rt.name);return e>-1?[...n.splice(e),Rt]:[...n,Rt]},"setupSystemNoVersion"),te=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ee("Gateway.constructor"),ge,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ee("Gateway.initialize"),n.#e||await Os.getTracer("gateway").startActiveSpan("gateway:initialize",{attributes:{[ge.SystemTrace]:!0}},async a=>{try{let u=await ln.init(r),c=e(),l={...c,corsPolicies:ss(c.corsPolicies)},d=new n(l,t,u,o);n.#e=d}finally{a.end()}}),!n.#e)throw new $("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ee("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new $("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Xt,Yt,re];#o;setupRoutes=()=>{Ee("Gateway.setupRoutes");let e=this.routeData,t=kc(e.versions),r=new At(t);if(e.routes.length===0)return fr(r,this),xr(r,this),Ir(r,this),as(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(bs(r,this),ys(r,this)),fr(r,this),xr(r,this),Ir(r,this);for(let s of xe)s instanceof Te&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new b(`Invalid state - No handler on route for path '${s.path}'`);let u=new Q({processors:this.#r,handler:a,gateway:this}),c=new Ve(s);r.addRoute(c,u.execute)}),us(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new b("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ee("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ee("Gateway.internalErrorResponse");let o={};if(R.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=ie(r.cause);"stack"in s&&(s.stack=Rs(s.stack)),o={cause:s}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;vs(r);let a=Ss({headers:e.headers,removeAllVendorHeadersExceptListed:R.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let P=new Headers(u.headers);P.set(Wn,"true"),u=new Request(u,{headers:P,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,g=this.#n.lookup(u.method,m);if(!g)throw new $(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let I=new pn(e.headers),y=new z(u,{params:g.params}),T=new mn({logger:l,route:g.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:I}),_=g.routeConfiguration.raw();Os.getActiveSpan()?.setAttributes({"http.route":T.route.path??T.route.pathPattern,"cloud.region":T.incomingRequestProperties.colo,[ge.RoutePathPattern]:T.route.pathPattern,[ge.RouteOperationId]:_.operationId,[ge.RouteTrace]:_["x-zuplo-trace"],[ge.RouteSystem]:Ye(p)?!0:void 0});let h=ne.initialize(T,y);if(g.routeConfiguration===Tr&&yt.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(m);h.pathOnlyMatches=P.map(S=>S.routeConfiguration).filter(S=>S instanceof Ve)}try{if(j.addLogger(T,d),R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!Ye(p):!p.pathname.startsWith("/__zuplo")){let f=await Ki(y,T);if(f instanceof Response)return f;{let w=ne.getContextExtensions(T);y=f,w.latestRequest=y}}Ye(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let P=g.executableHandler;Mc(P,g,u),Ee("Gateway.handleRequest - call user handler");let S=await P(y,T);if(Ee("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let H;if(S.headers.get(qe)===null&&!S.webSocket){let f=new Headers(S.headers);f.set(qe,o),H=new Response(S.body,{status:S.status,statusText:S.statusText,headers:f,cf:S.cf})}else H=S;return H}catch(P){return Ee("Gateway - error executing handler",P),P instanceof A?(l.error(P),d.warn(P)):d.error(P),await this.#i(y,T,P)}}};function Mc(n,e,t){if(Ee("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new b(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new b(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(Mc,"checkHandler");var As=i(async(n,e,t)=>{let r=te.instance.routeData.policies,o=Et([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var pn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(er);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(tr)??void 0}get city(){return this.#e.get(Jn)??this.#e.get(Ui)??void 0}get continent(){return this.#e.get(Kn)??this.#e.get(Hi)??void 0}get country(){return this.#e.get(Yn)??this.#e.get(Zi)??void 0}get latitude(){return this.#e.get(Xn)??this.#e.get($i)??void 0}get longitude(){return this.#e.get(Qn)??this.#e.get(qi)??void 0}get colo(){return this.#e.get(nr)??void 0}get postalCode(){return this.#e.get(Mi)??this.#e.get(rr)??void 0}get metroCode(){return this.#e.get(ki)??this.#e.get(or)??void 0}get region(){return this.#e.get(Li)??this.#e.get(ir)??void 0}get regionCode(){return this.#e.get(Ni)??this.#e.get(sr)??void 0}get timezone(){return this.#e.get(Di)??this.#e.get(ar)??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}}},bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},wt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ne=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},mn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>As(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ne.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ne.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fe=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)}};var Dc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Uc(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Dc.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Uc,"isRestrictedEnvVariableName");function Hc(n){return!!n.startsWith("ZUPLO_")}i(Hc,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(n,e){if(!(Uc(String(e))&&!Hc(String(e))))return R.instance.runtime[String(e)]}});import{AsyncLocalStorage as Zc}from"node:async_hooks";var _s={request:new Zc};var qc="Error initializing gateway. Check your configuration for errors or contact support.",$c="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",jr=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(qe)??e.headers.get(Ai)??crypto.randomUUID(),s=e.headers.get($e),a={requestId:o,rayId:s};return _s.request.run(a,async()=>{R.initialize({build:this.buildEnvironment,runtime:t});try{await Xi(this.runtimeInit)}catch(c){this.handleError(c,$c,e)}return Wi(i(async(c,l)=>{let d;try{d=await te.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,qc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof b&&(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:R.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var qs=Oe(_e());function Fc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(Fc,"lexer");function zr(n,e){e===void 0&&(e={});for(var t=Fc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(jc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(f){if(c<t.length&&t[c].type===f)return t[c++].value},"tryConsume"),p=i(function(f){var w=d(f);if(w!==void 0)return w;var O=t[c],D=O.type,C=O.index;throw new TypeError("Unexpected ".concat(D," at ").concat(C,", expected ").concat(f))},"mustConsume"),m=i(function(){for(var f="",w;w=d("CHAR")||d("ESCAPED_CHAR");)f+=w;return f},"consumeText");c<t.length;){var g=d("CHAR"),I=d("NAME"),y=d("PATTERN");if(I||y){var T=g||"";o.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:I||u++,prefix:T,suffix:"",pattern:y||s,modifier:d("MODIFIER")||""});continue}var _=g||d("ESCAPED_CHAR");if(_){l+=_;continue}l&&(a.push(l),l="");var h=d("OPEN");if(h){var T=m(),P=d("NAME")||"",S=d("PATTERN")||"",H=m();p("CLOSE"),a.push({name:P||(S?u++:""),pattern:P&&!S?s:S,prefix:T,suffix:H,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(zr,"parse");function Ls(n,e){return Bc(zr(n,e),e)}i(Ls,"compile");function Bc(n,e){e===void 0&&(e={});var t=zc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var y=0;y<m.length;y++){var T=o(m[y],p);if(a&&!u[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=o(String(m),p);if(a&&!u[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!g){var _=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(_))}}return l}}i(Bc,"tokensToFunction");function jc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(jc,"escapeString");function zc(n){return n&&n.sensitive?"":"i"}i(zc,"flags");var Ds=Oe(_e());var Vc=(0,Ds.debug)("zuplo:runtime"),Gr=new TextEncoder,Ns={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"},Gc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],tt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Wr(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){Vc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=M.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new b("An unknown error occurred, ensure retries is not negative")}},Wr=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:g,allHeaders:I,singleEncode:y}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let T,_;(!c||!l)&&([T,_]=Wc(this.url,this.headers)),this.service=c||T||"",this.region=l||_||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let h=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"),h.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&h.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>I||!Gc.includes(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
63
63
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.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,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ms(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>Ms(encodeURIComponent(H)))).sort(([S,H],[f,w])=>S<f?-1:S>f?1:H<w?-1:H>w?1:0).map(S=>S.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 _t("AWS4"+this.secretAccessKey,e),s=await _t(o,this.region),a=await _t(s,this.service);r=await _t(a,"aws4_request"),this.cache.set(t,r)}return Vr(await _t(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Vr(await ks(await this.canonicalString()))].join(`
64
64
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
65
65
  `,this.signedHeaders,await this.hexBodyHash()].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.2071.0",
3
+ "version": "5.2073.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {