@zuplo/runtime 5.2428.0 → 5.2430.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/index.js +1 -1
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -43,7 +43,7 @@ import{a as Ze,d as Pe,e as Ra,f as Mn,g as qn,h as Pa,i as Ia}from"./chunk-BGTP
|
|
|
43
43
|
`,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 f=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let O=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
44
44
|
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(o.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||qi(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>r)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";o.push(a);let y="["+p.newline+a.map((O,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(O,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return o.pop(),f(y)}if(et(a)){let y=Hi(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";o.push(a);let O="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",j=!A&&/^[a-z$_][$\w]*$/i.test(P),q=A||j?P:s(P,u,"",l+1),Z=s(a[P],u,c+d,l+1);return u.transform&&(Z=u.transform(a,P,Z)),p.indent+String(q)+": "+Z+N}).join("")+p.pad+"}";return o.pop(),f(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
45
45
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(ln,"stringifyObject");function Ge(n){return n.map(e=>Ie(e))}i(Ge,"makeErrorsSerializable");function ct(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:Ue(Ie(e))}i(ct,"extractBestMessage");function os(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Nt(t))if(t.stack)e.push(t.stack);else{let o=ln(Ie(t));e.push(o)}else if(typeof t=="object"){let o=ln(t);e.push(o)}else{let o=To(t);e.push(o)}}),e.join(`
|
|
46
|
-
`)}i(os,"messagesToMultilineText");function Ue(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ue,"stringifyNonString");function To(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"?lo(n):"unknown"}i(To,"stringifyNonStringToText");import{importPKCS8 as Xa,SignJWT as eu}from"jose";async function fe(n,e,t){for(let o=0;o<=n.retries;o++){let r=$.fetch(e,t);if(o===n.retries)return r;let s=await r;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,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(fe,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new eu(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function rs(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return vo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(rs,"exchangeIDTokenForGcpWorkloadToken");async function is({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return as(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}i(is,"generateServiceAccountIDToken");async function ss(n,e,t){return vo(n,{token:e,returnSecureToken:!0},t)}i(ss,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return vo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(dn,"exchangeGgpJwtForIdToken");async function vo(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return as(n,o,t)}i(vo,"fetchTokenFromBody");async function as(n,e,t){let o=await fe(t,n,e);if(o.status!==200){let s;try{let a=await o.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await o.json()}i(as,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await Xa(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function le(n){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...n,vectorClock:0};await us({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function us({loggingUrl:n,loggingId:e,loggingToken:t},o){try{await $.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(r=>({...r,messages:Ge(r.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(us,"sendRemoteLogs");var tu=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:o})=>async r=>{let s;o===!0?s=r.filter(a=>a.level==="error"):s=r,s.length!==0&&await us({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),pn,mn=class{static{i(this,"RemoteLogTransport")}constructor(e){pn||(pn=new Y("remote-log-transport",1,tu(e)))}log(e,t){pn.enqueue(e),t.waitUntil(pn.waitUntilFlushed())}};var Co=class extends ge{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ht(this.options)}},nu="https://logging.googleapis.com/v2/entries:write?alt=json",So={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ht=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new J("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:Ge(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:So[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ct(o.allMessages);s.jsonPayload={...o,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await $.fetch(nu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var gn="gcp";function fn(n){let e={allMessages:Ge(n.messages)},t="zuplo-production",o=ct(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,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&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}i(fn,"gcpLogFormat");var Ut=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(e)])}else this.#e.log(JSON.stringify(e))}};var Lo=class extends ge{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Zt(this.options)}},Oo="__ddtags",Ao="__ddattr",ko=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ou=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(ko(o)):t.push(`${ko(o)}:${ko(r.toString())}`)}),t.join(",")},"formatTags"),Zt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Oo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Oo]!==void 0);a>-1&&(Object.assign(o,s[a][Oo]),s.splice(a,1));let u={},c=t.custom[Ao];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ao]!==void 0);l>-1&&(Object.assign(u,s[l][Ao]),s.splice(l,1));let d=Ge(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ct(d),service:e.loggingId,ddtags:ou(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Ft=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(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 ru={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},cs=i((n,e)=>t=>{let o={};return o.deploymentName=n,o.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},o.rayId=t.rayId??"",o.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},o.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ru[t.level],body:t.messages,attributes:o}},"unifiedFormatter");var iu=i(({url:n,remoteLogToken:e,deploymentName:t,build:o})=>async r=>{if(r.length===0)return;let s=cs(t,o);try{await $.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:r.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),hn,yn=class{static{i(this,"UnifiedLogTransport")}constructor(e){hn||(hn=new Y("unified-log-transport",1,iu(e)))}async log(e,t){hn.enqueue(e),t.waitUntil(hn.waitUntilFlushed())}};var _o=Re("zuplo:logging"),bn=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(h.instance,e),o=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;_o("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(Jt);return s?r.push(new Ft(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ut(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new yn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Mt(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){_o("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(Jt);if(a&&a.captureUserLogs===!0?o.push(new Ft(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ut(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&o.push(new mn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Ht({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Zt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof ge&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new Mt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s){_o("Gateway.createRequestLoggers");let a=new cn(o,r,s),u=new qt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new qt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ot=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 No=class{static{i(this,"RouterEntry")}constructor(e,t,o,r){this.fullPath=e,this.urlPattern=t,this.config=o,this.executableHandler=r}fullPath;urlPattern;config;executableHandler},$t=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Do=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},jt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ot||e instanceof ce))throw new J("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o=this.versions.find(s=>s.name===e.version)?.pathPrefix,r;"pathPattern"in e&&e.pathPattern?r=`${o??""}${e.pathPattern}`:r=`${o??""}${e.path}`;try{let s=new URLPattern({pathname:r}),a=new No(r,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Do(`addRoute-error: Invalid path '${r}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let o=this.routeEntries.filter(r=>r.config.methods.includes(e));if(o.length!==0)for(let r=0;r<o.length;r++){let s=o[r],u=s.urlPattern.exec({pathname:t});if(u!==null)return new $t(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],a=r.urlPattern.exec({pathname:e});if(a!==null){let u=new $t(r.config,r.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Mo;function ls(n){Mo=n}i(ls,"setGlobalZuploEventContext");function wn(){if(Mo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Mo}i(wn,"getGlobalZuploEventContext");function ds({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);Ei.includes(r.toLowerCase())&&!xi.includes(o.toLowerCase())&&t.delete(o)}t.delete(li)}else Ii.forEach(o=>{t.delete(o)});return t}i(ds,"normalizeIncomingRequestHeaders");var De=Re("zuplo:runtime"),au=i(n=>{let e=n.findIndex(t=>t.name===_t.name);return e>-1?[...n.splice(e),_t]:[...n,_t]},"setupSystemNoVersion"),he=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#r=this.setupErrorHandler(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(De("Gateway.initialize"),!n.#e){let s=await bn.init(o),a=e(),u={...a,corsPolicies:$i(a.corsPolicies)},c=new n(u,t,s,r);n.#e=c}if(!n.#e)throw new J("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new J("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[un,sn,be];#r;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=au(e.versions),o=new jt(t);if(e.routes.length===0)return co(o,this),yo(o,this),fo(o,this),ji(o,this),o;let{enabled:r}=this.runtimeSettings.developerPortal;r&&(es(o,this),Xi(o,this)),co(o,this),yo(o,this),fo(o,this);for(let s of He)s instanceof qe&&s.registerRoutes(o,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#o,handler:a,gateway:this}),c=new ot(s);o.addRoute(c,u.execute)}),zi(o,this),o},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,o,r)=>this.#i(t,o,r),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,o){try{return this.#r(e,t,o)}catch(r){return De("An error occurred in the user's errorHandler",r),this.#i(e,t,r)}}#i(e,t,o){De("Gateway.internalErrorResponse");let r={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(o instanceof L&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let s=Ie(o.cause);"stack"in s&&(s.stack=ns(s.stack)),r={cause:s}}}return x.internalServerError(e,t,{detail:o.message,...r})}async handleRequest(e,t,o){let{requestId:r,rayId:s}=t;ls(o);let a=ds({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Qe,r);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Zn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(r,s,o,c,u),p=new URL(u.url),f=p.pathname,y=this.#n.lookup(u.method,f);if(!y)throw new J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let O=new Rn(e.headers),P=new te(u,{params:y.params}),v=new Pn({logger:l,route:y.routeConfiguration,requestId:r,event:o,custom:c,incomingRequestProperties:O}),N=y.routeConfiguration.raw();su.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:at(p)?!0:void 0});let A=ye.initialize(v,P);if(y.routeConfiguration===ho&&At.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(f);A.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof ot)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!at(p):!p.pathname.startsWith("/__zuplo")){let E=await Li(P,v);if(E instanceof Response)return E;{let H=ye.getContextExtensions(v);P=E,H.latestRequest=P}}at(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;uu(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let Z;if(q.headers.get(Qe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Qe,r),Z=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else Z=q;return Z}catch(j){return De("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function uu(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(uu,"checkHandler");var ps=i(async(n,e,t)=>{let o=he.instance.routeData.policies,r=Dt([n],o);if(r.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy");var Rn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Gn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Vn)??void 0}get city(){return this.#e.get(Fn)??this.#e.get(hi)??void 0}get continent(){return this.#e.get($n)??this.#e.get(yi)??void 0}get country(){return this.#e.get(jn)??this.#e.get(bi)??void 0}get latitude(){return this.#e.get(Bn)??this.#e.get(Ri)??void 0}get longitude(){return this.#e.get(zn)??this.#e.get(wi)??void 0}get colo(){return this.#e.get(Wn)??void 0}get postalCode(){return this.#e.get(gi)??this.#e.get(Kn)??void 0}get metroCode(){return this.#e.get(mi)??this.#e.get(Jn)??void 0}get region(){return this.#e.get(di)??this.#e.get(Qn)??void 0}get regionCode(){return this.#e.get(pi)??this.#e.get(Yn)??void 0}get timezone(){return this.#e.get(fi)??this.#e.get(Xn)??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}}},kt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Lt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}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 L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)},"onResponseSendingFinal");onResponseSending=i(async(e,t,o)=>{let r=e;for(let s of this.#n)r=await s(e,t,o);return r},"onResponseSending")},Pn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>ps(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=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,r,o)}};var se=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,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{AsyncLocalStorage as cu}from"node:async_hooks";var ms={request:new cu};var lu="Error initializing gateway. Check your configuration for errors or contact support.",du="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",qo=class{constructor(e,t,o,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,o)=>{let r=e.headers.get(Qe)??e.headers.get(ci)??crypto.randomUUID(),s=e.headers.get(Ye),a={requestId:r,rayId:s};return ms.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await Di(this.runtimeInit)}catch(c){this.handleError(c,du,e)}return Ci(i(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,lu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,o)})},"requestHandler");handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function pu(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",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){r+=n[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(o==="("){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(pu,"lexer");function Ho(n,e){e===void 0&&(e={});for(var t=pu(n),o=e.prefixes,r=o===void 0?"./":o,s="[^".concat(gu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),f=i(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var v=y||"";r.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var v=f(),j=d("NAME")||"",q=d("PATTERN")||"",Z=f();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:Z,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Ho,"parse");function gs(n,e){return mu(Ho(n,e),e)}i(gs,"compile");function mu(n,e){e===void 0&&(e={});var t=fu(e),o=e.encode,r=o===void 0?function(c){return c}:o,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 f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var v=r(f[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var v=r(String(f),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(mu,"tokensToFunction");function gu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(gu,"escapeString");function fu(n){return n&&n.sensitive?"":"i"}i(fu,"flags");var hu=Re("zuplo:runtime"),Zo=new TextEncoder,fs={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"},yu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],lt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,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=o,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new Fo(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){hu("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=$.fetch(r,s);if(o===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,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Fo=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:o,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:O,singleEncode:P}){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||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=bu(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!yu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
|
|
46
|
+
`)}i(os,"messagesToMultilineText");function Ue(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ue,"stringifyNonString");function To(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"?lo(n):"unknown"}i(To,"stringifyNonStringToText");import{importPKCS8 as Xa,SignJWT as eu}from"jose";async function fe(n,e,t){for(let o=0;o<=n.retries;o++){let r=$.fetch(e,t);if(o===n.retries)return r;let s=await r;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,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(fe,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:s,privateKey:a}=n;return await new eu(o).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function rs(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return vo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(rs,"exchangeIDTokenForGcpWorkloadToken");async function is({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return as(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}i(is,"generateServiceAccountIDToken");async function ss(n,e,t){return vo(n,{token:e,returnSecureToken:!0},t)}i(ss,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return vo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(dn,"exchangeGgpJwtForIdToken");async function vo(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return as(n,o,t)}i(vo,"fetchTokenFromBody");async function as(n,e,t){let o=await fe(t,n,e);if(o.status!==200){let s;try{let a=await o.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await o.json()}i(as,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await Xa(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function le(n){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...n,vectorClock:0};await us({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function us({loggingUrl:n,loggingId:e,loggingToken:t},o){try{await $.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(r=>({...r,messages:Ge(r.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(us,"sendRemoteLogs");var tu=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:o})=>async r=>{let s;o===!0?s=r.filter(a=>a.level==="error"):s=r,s.length!==0&&await us({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),pn,mn=class{static{i(this,"RemoteLogTransport")}constructor(e){pn||(pn=new Y("remote-log-transport",1,tu(e)))}log(e,t){pn.enqueue(e),t.waitUntil(pn.waitUntilFlushed())}};var Co=class extends ge{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ht(this.options)}},nu="https://logging.googleapis.com/v2/entries:write?alt=json",So={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ht=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new J("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:Ge(e.messages)},r=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:So[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=ct(o.allMessages);s.jsonPayload={...o,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await $.fetch(nu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var gn="gcp";function fn(n){let e={allMessages:Ge(n.messages)},t="zuplo-production",o=ct(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,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&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}i(fn,"gcpLogFormat");var Ut=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(e)])}else this.#e.log(JSON.stringify(e))}};var Lo=class extends ge{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Zt(this.options)}},Oo="__ddtags",Ao="__ddattr",ko=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ou=i(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(ko(o)):t.push(`${ko(o)}:${ko(r.toString())}`)}),t.join(",")},"formatTags"),Zt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Oo];r&&typeof r=="object"&&Object.assign(o,r);let s=[...e.messages],a=e.messages.findIndex(y=>y[Oo]!==void 0);a>-1&&(Object.assign(o,s[a][Oo]),s.splice(a,1));let u={},c=t.custom[Ao];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Ao]!==void 0);l>-1&&(Object.assign(u,s[l][Ao]),s.splice(l,1));let d=Ge(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:ct(d),service:e.loggingId,ddtags:ou(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Ft=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(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 ru={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},cs=i((n,e)=>t=>{let o={};return o.deploymentName=n,o.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},o.rayId=t.rayId??"",o.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},o.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ru[t.level],body:t.messages,attributes:o}},"unifiedFormatter");var iu=i(({url:n,remoteLogToken:e,deploymentName:t,build:o})=>async r=>{if(r.length===0)return;let s=cs(t,o);try{await $.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:r.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),hn,yn=class{static{i(this,"UnifiedLogTransport")}constructor(e){hn||(hn=new Y("unified-log-transport",1,iu(e)))}async log(e,t){hn.enqueue(e),t.waitUntil(hn.waitUntilFlushed())}};var _o=Re("zuplo:logging"),bn=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(h.instance,e),o=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;_o("Gateway.setupSystemCoreLogger");let r=[],s=t.getService(Jt);return s?r.push(new Ft(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ut(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new yn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new Mt(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){_o("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=t.getService(Jt);if(a&&a.captureUserLogs===!0?o.push(new Ft(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ut(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&o.push(new mn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Ht({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Zt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof ge&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new Mt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,t,o,r,s){_o("Gateway.createRequestLoggers");let a=new cn(o,r,s),u=new qt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new qt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ot=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 No=class{static{i(this,"RouterEntry")}constructor(e,t,o,r){this.fullPath=e,this.urlPattern=t,this.config=o,this.executableHandler=r}fullPath;urlPattern;config;executableHandler},$t=class{static{i(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Do=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},jt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ot||e instanceof ce))throw new J("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o=this.versions.find(s=>s.name===e.version)?.pathPrefix,r;"pathPattern"in e&&e.pathPattern?r=`${o??""}${e.pathPattern}`:r=`${o??""}${e.path}`;try{let s=new URLPattern({pathname:r}),a=new No(r,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Do(`addRoute-error: Invalid path '${r}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let o=this.routeEntries.filter(r=>r.config.methods.includes(e));if(o.length!==0)for(let r=0;r<o.length;r++){let s=o[r],u=s.urlPattern.exec({pathname:t});if(u!==null)return new $t(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],a=r.urlPattern.exec({pathname:e});if(a!==null){let u=new $t(r.config,r.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Mo;function ls(n){Mo=n}i(ls,"setGlobalZuploEventContext");function wn(){if(Mo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Mo}i(wn,"getGlobalZuploEventContext");function ds({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);Ei.includes(r.toLowerCase())&&!xi.includes(o.toLowerCase())&&t.delete(o)}t.delete(li)}else Ii.forEach(o=>{t.delete(o)});return t}i(ds,"normalizeIncomingRequestHeaders");var De=Re("zuplo:runtime"),au=i(n=>{let e=n.findIndex(t=>t.name===_t.name);return e>-1?[...n.splice(e),_t]:[...n,_t]},"setupSystemNoVersion"),he=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#r=this.setupErrorHandler(),this.#t=o}static{i(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(De("Gateway.initialize"),!n.#e){let s=await bn.init(o),a=await e(),u={...a,corsPolicies:$i(a.corsPolicies)},c=new n(u,t,s,r);n.#e=c}if(!n.#e)throw new J("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new J("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[un,sn,be];#r;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=au(e.versions),o=new jt(t);if(e.routes.length===0)return co(o,this),yo(o,this),fo(o,this),ji(o,this),o;let{enabled:r}=this.runtimeSettings.developerPortal;r&&(es(o,this),Xi(o,this)),co(o,this),yo(o,this),fo(o,this);for(let s of He)s instanceof qe&&s.registerRoutes(o,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#o,handler:a,gateway:this}),c=new ot(s);o.addRoute(c,u.execute)}),zi(o,this),o},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,o,r)=>this.#i(t,o,r),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,o){try{return this.#r(e,t,o)}catch(r){return De("An error occurred in the user's errorHandler",r),this.#i(e,t,r)}}#i(e,t,o){De("Gateway.internalErrorResponse");let r={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(o instanceof L&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let s=Ie(o.cause);"stack"in s&&(s.stack=ns(s.stack)),r={cause:s}}}return x.internalServerError(e,t,{detail:o.message,...r})}async handleRequest(e,t,o){let{requestId:r,rayId:s}=t;ls(o);let a=ds({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Qe,r);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Zn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(r,s,o,c,u),p=new URL(u.url),f=p.pathname,y=this.#n.lookup(u.method,f);if(!y)throw new J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let O=new Rn(e.headers),P=new te(u,{params:y.params}),v=new Pn({logger:l,route:y.routeConfiguration,requestId:r,event:o,custom:c,incomingRequestProperties:O}),N=y.routeConfiguration.raw();su.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:at(p)?!0:void 0});let A=ye.initialize(v,P);if(y.routeConfiguration===ho&&At.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(f);A.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof ot)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!at(p):!p.pathname.startsWith("/__zuplo")){let E=await Li(P,v);if(E instanceof Response)return E;{let H=ye.getContextExtensions(v);P=E,H.latestRequest=P}}at(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;uu(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let Z;if(q.headers.get(Qe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Qe,r),Z=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else Z=q;return Z}catch(j){return De("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function uu(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(uu,"checkHandler");var ps=i(async(n,e,t)=>{let o=he.instance.routeData.policies,r=Dt([n],o);if(r.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy");var Rn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Gn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Vn)??void 0}get city(){return this.#e.get(Fn)??this.#e.get(hi)??void 0}get continent(){return this.#e.get($n)??this.#e.get(yi)??void 0}get country(){return this.#e.get(jn)??this.#e.get(bi)??void 0}get latitude(){return this.#e.get(Bn)??this.#e.get(Ri)??void 0}get longitude(){return this.#e.get(zn)??this.#e.get(wi)??void 0}get colo(){return this.#e.get(Wn)??void 0}get postalCode(){return this.#e.get(gi)??this.#e.get(Kn)??void 0}get metroCode(){return this.#e.get(mi)??this.#e.get(Jn)??void 0}get region(){return this.#e.get(di)??this.#e.get(Qn)??void 0}get regionCode(){return this.#e.get(pi)??this.#e.get(Yn)??void 0}get timezone(){return this.#e.get(fi)??this.#e.get(Xn)??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}}},kt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Lt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}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 L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)},"onResponseSendingFinal");onResponseSending=i(async(e,t,o)=>{let r=e;for(let s of this.#n)r=await s(e,t,o);return r},"onResponseSending")},Pn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>ps(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=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,r,o)}};var se=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,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{AsyncLocalStorage as cu}from"node:async_hooks";var ms={request:new cu};var lu="Error initializing gateway. Check your configuration for errors or contact support.",du="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",qo=class{constructor(e,t,o,r,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,o)=>{let r=e.headers.get(Qe)??e.headers.get(ci)??crypto.randomUUID(),s=e.headers.get(Ye),a={requestId:r,rayId:s};return ms.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await Di(this.runtimeInit)}catch(c){this.handleError(c,du,e)}return Ci(i(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,lu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,o)})},"requestHandler");handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};function pu(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",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){r+=n[s++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=s;continue}if(o==="("){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(pu,"lexer");function Ho(n,e){e===void 0&&(e={});for(var t=pu(n),o=e.prefixes,r=o===void 0?"./":o,s="[^".concat(gu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),f=i(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var v=y||"";r.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var v=f(),j=d("NAME")||"",q=d("PATTERN")||"",Z=f();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:Z,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Ho,"parse");function gs(n,e){return mu(Ho(n,e),e)}i(gs,"compile");function mu(n,e){e===void 0&&(e={});var t=fu(e),o=e.encode,r=o===void 0?function(c){return c}:o,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 f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var v=r(f[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var v=r(String(f),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(mu,"tokensToFunction");function gu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(gu,"escapeString");function fu(n){return n&&n.sensitive?"":"i"}i(fu,"flags");var hu=Re("zuplo:runtime"),Zo=new TextEncoder,fs={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"},yu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],lt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,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=o,this.service=r,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new Fo(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){hu("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:s}=await this.sign(e,t),a=$.fetch(r,s);if(o===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,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Fo=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:o,body:r,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:O,singleEncode:P}){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||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=bu(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!yu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
|
|
47
47
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ys(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map(Z=>ys(encodeURIComponent(Z)))).sort(([q,Z],[E,H])=>q<E?-1:q>E?1:Z<H?-1:Z>H?1:0).map(q=>q.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(),o=this.cache.get(t);if(!o){let r=await zt("AWS4"+this.secretAccessKey,e),s=await zt(r,this.region),a=await zt(s,this.service);o=await zt(a,"aws4_request"),this.cache.set(t,o)}return Uo(await zt(o,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Uo(await hs(await this.canonicalString()))].join(`
|
|
48
48
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
49
49
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|