@zuplo/runtime 6.40.7 → 6.40.8
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
|
@@ -62,7 +62,7 @@ import{a as y,b as Ue,e as fe,f as Cu,g as Xn,h as er,i as Au,j as Ou}from"./chu
|
|
|
62
62
|
`,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(f=>{if(u.inlineCharacterLimit===void 0)return f;let P=f.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return P.length<=u.inlineCharacterLimit?P:f.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
63
63
|
`).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 f="["+p.newline+a.map((P,b)=>{let v=a.length-1===b?p.newline:","+p.newlineOrSpace,L=s(P,u,c+d,l+1);return u.transform&&(L=u.transform(a,b,L)),p.indent+L+v}).join("")+p.pad+"]";return r.pop(),m(f)}if(ot(a)){let f=As(a);if(u.filter&&(f=f.filter(b=>u.filter?.(a,b))),f.length===0)return"{}";r.push(a);let P="{"+p.newline+f.map((b,v)=>{let L=f.length-1===v?p.newline:","+p.newlineOrSpace,C=typeof b=="symbol",$=!C&&/^[a-z$_][$\w]*$/i.test(b),F=C||$?b:s(b,u,"",l+1),q=s(a[b],u,c+d,l+1);return u.transform&&(q=u.transform(a,b,q)),p.indent+String(F)+": "+q+L}).join("")+p.pad+"}";return r.pop(),m(P)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,f=>f===`
|
|
64
64
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Sn,"stringifyObject");function Fe(n){return Xs(at(n))}i(Fe,"serializeMessage");function Ne(n){return n.map(e=>Fe(e))}i(Ne,"serializeMessages");function yt(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:Xs(at(e))}i(yt,"extractBestMessage");function Ys(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ft(t))if(t.stack)e.push(t.stack);else{let r=Sn(at(t));e.push(r)}else if(typeof t=="object"){let r=Sn(t);e.push(r)}else{let r=eo(t);e.push(r)}}),e.join(`
|
|
65
|
-
`)}i(Ys,"messagesToMultilineText");function Xs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Xs,"stringifyNonString");function eo(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"?Hr(n):"unknown"}i(eo,"stringifyNonStringToText");import{importPKCS8 as Dc,SignJWT as Mc}from"jose";async function Re(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(Re,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Mc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function ea(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return to("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(ea,"exchangeIDTokenForGcpWorkloadToken");async function ta({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ra(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ta,"generateServiceAccountIDToken");async function na(n,e,t){return to(n,{token:e,returnSecureToken:!0},t)}i(na,"exchangeFirebaseJwtForIdToken");async function vn(n,e,t){return to(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(vn,"exchangeGgpJwtForIdToken");async function to(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return ra(n,r,t)}i(to,"fetchTokenFromBody");async function ra(n,e,t){let r=await Re(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ra,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Dc(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 qc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},oa=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:qc[e.level],body:Ne(e.messages),attributes:t}},"unifiedFormatter");async function te(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await ia(y.instance,[r])}catch(r){console.error(r)}}i(te,"sendRemoteGlobalLog");async function ia(n,e){let t=oa(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});_e(r),await Z.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ia,"sendLogs");var Uc=i(n=>async e=>{e.length!==0&&await ia(n,e)},"dispatchFunction"),Cn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Cn||(Cn=new Y("unified-log-transport",1,Uc(e)))}log(e,t){Cn.enqueue(e),t.waitUntil(Cn.waitUntilFlushed())}};var no=class extends be{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Wt(this.options)}},Hc="https://logging.googleapis.com/v2/entries:write?alt=json",ro={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Wt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,h("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ne(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ro[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=yt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(Hc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await te({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await te({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 An="gcp";function On(n){let e={allMessages:Ne(n.messages)},t="zuplo-production",r=yt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:ro[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 Jt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level](On(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ne(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var ao=class extends be{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Kt(this.options)}},oo="__ddtags",io="__ddattr",so=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),$c=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(so(r)):t.push(`${so(r)}:${so(o.toString())}`)}),t.join(",")},"formatTags"),Kt=class{static{i(this,"DataDogTransport")}constructor(e){h("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[oo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(f=>f[oo]!==void 0);a>-1&&(Object.assign(r,s[a][oo]),s.splice(a,1));let u={},c=t.custom[io];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(f=>f[io]!==void 0);l>-1&&(Object.assign(u,s[l][io]),s.splice(l,1));let d=Ne(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:yt(d),service:e.loggingId,ddtags:$c(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=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await te({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await te({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 Qt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===An){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 uo=we("zuplo:logging"),kn=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(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;uo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(mn);return s?o.push(new Qt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Bt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){uo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(mn);if(a&&a.captureUserLogs===!0?r.push(new Qt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Vt(e)),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(h("logging.google.legacy-initialization"),r.push(new Wt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){h("logging.datadog.legacy-initialization");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 He.forEach(u=>{u instanceof be&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Bt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){uo("Gateway.createRequestLoggers");let u=new Tn(r,o,s,a),c=new Gt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Gt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Ln=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var co=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r,this.urlPattern=new URLPattern({pathname:this.fullPath})}urlPattern;fullPath;config;executableHandler},_n=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof We||e instanceof ue))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new co(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Ln(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as Zc}from"node:async_hooks";var Nn={context:new Zc};var lo;function sa(n){lo=n}i(sa,"setGlobalZuploEventContext");function Ke(){if(lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return lo}i(Ke,"getGlobalZuploEventContext");function aa({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);gs.includes(o.toLowerCase())&&!fs.includes(r.toLowerCase())&&t.delete(r)}t.delete(ts)}else ms.forEach(r=>{t.delete(r)});return t}i(aa,"normalizeIncomingRequestHeaders");var Qe=we("zuplo:runtime"),he=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Qe("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Qe("Gateway.initialize"),!n.#e){let s=await kn.init(r),a=await e(),u={...a,corsPolicies:_s(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Qe("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[st,In,ye];setupRoutes=i(()=>{Qe("Gateway.setupRoutes");let e=this.routeData,t=new _n;if(e.routes.length===0)return Mr(t,this),zr(t,this),jr(t,this),Ns(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&(o==="zudoku"?(Js(t,this),Ks(t,this)):o==="legacy"&&(Ws(t,this),Vs(t,this))),Mr(t,this),zr(t,this),jr(t,this);for(let s of He)s instanceof ge&&s.registerRoutes(t,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 g(`Invalid state - No handler on route for path '${s.path}'`);let u=new de({processors:this.#r,handler:a,gateway:this}),c=new We(s);t.addRoute(c,u.execute)}),Ds(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Qe("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=at(o.cause);"stack"in a&&(a.stack=Xr(a.stack)),s={cause:a}}else{let a=at(o);"stack"in a&&(a.stack=Xr(a.stack)),s={cause:a}}return x.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t){let r=e.headers.get(gt)??e.headers.get(es)??crypto.randomUUID(),o=e.headers.get(nt);sa(t);let s=aa({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(gt,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let C=new Headers(a.headers);C.set(gr,"true"),a=new Request(a,{headers:C,body:null})}let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:m}=this.#t.createRequestLoggers(r,o,t,d,a,l.routeConfiguration),f=new Dn(e.headers),P=new ne(a,{params:l.params}),b=new Mn({logger:p,route:l.routeConfiguration,requestId:r,event:t,custom:d,incomingRequestProperties:f}),v=Nn.context.getStore();v&&(v.context=b);let L=l.routeConfiguration.raw();Fc.getActiveSpan()?.setAttributes({"http.route":b.route.path??b.route.pathPattern,"cloud.region":b.incomingRequestProperties.colo,[Ze.RoutePathPattern]:b.route.pathPattern,[Ze.RouteOperationId]:L.operationId,[Ze.RouteTrace]:L["x-zuplo-trace"],[Ze.RouteSystem]:ft(u)?!0:void 0}),Ee.initialize(b,P);try{if(Q.addLogger(b,m),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!ft(u):!u.pathname.startsWith("/__zuplo")){let q=await Es(P,b);if(q instanceof Response)return q;{let A=Ee.getContextExtensions(b);P=q,A.latestRequest=P}}ft(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let C=l.executableHandler;jc(C,l,a),Qe("Gateway.handleRequest - call user handler");let $=await C(P,b);if(Qe("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if($.headers.get(gt)===null&&!$.webSocket){let q=new Headers($.headers);q.set(gt,r),F=new Response($.body,{status:$.status,statusText:$.statusText,headers:q,cf:$.cf})}else F=$;return F}catch(C){return C instanceof k?(p.error(C),m.warn(C)):m.error(C),await this.errorHandler(P,b,"Error executing handler",C)}}};function jc(n,e,t){if(Qe("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(jc,"checkHandler");var ua=i(async(n,e,t)=>{let r=he.instance.routeData.policies,o=jt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),ca=i(async(n,e,t,r)=>{let o=he.instance.routeData.policies,s=zt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var Dn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Rr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Pr)??void 0}get city(){return this.#e.get(fr)??this.#e.get(as)??void 0}get continent(){return this.#e.get(hr)??this.#e.get(us)??void 0}get country(){return this.#e.get(yr)??this.#e.get(cs)??void 0}get latitude(){return this.#e.get(wr)??this.#e.get(ds)??void 0}get longitude(){return this.#e.get(br)??this.#e.get(ls)??void 0}get colo(){return this.#e.get(Ir)??void 0}get postalCode(){return this.#e.get(is)??this.#e.get(Er)??void 0}get metroCode(){return this.#e.get(os)??this.#e.get(xr)??void 0}get region(){return this.#e.get(ns)??this.#e.get(Tr)??void 0}get regionCode(){return this.#e.get(rs)??this.#e.get(Sr)??void 0}get timezone(){return this.#e.get(ss)??this.#e.get(vr)??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}}},$t=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Zt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ee=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 k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},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)=>ua(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>ca(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ee.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var zc="Error initializing gateway. Check your configuration for errors or contact support.",Bc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",po=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await Ss(this.runtimeInit)}catch(s){this.handleError(s,Bc,e)}return bs(i(async(s,a)=>{let u;try{u=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,zc,s)}let c={context:void 0};return Nn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Gc(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(Gc,"lexer");function go(n,e){e===void 0&&(e={});for(var t=Gc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var T=p(j);if(T!==void 0)return T;var E=t[l],M=E.type,le=E.index;throw new TypeError("Unexpected ".concat(M," at ").concat(le,", expected ").concat(j))},"mustConsume"),f=i(function(){for(var j="",T;T=p("CHAR")||p("ESCAPED_CHAR");)j+=T;return j},"consumeText"),P=i(function(j){for(var T=0,E=a;T<E.length;T++){var M=E[T];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),b=i(function(j){var T=u[u.length-1],E=j||(T&&typeof T=="string"?T:"");if(T&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(T.name,'"'));return!E||P(E)?"[^".concat(mo(a),"]+?"):"(?:(?!".concat(mo(E),")[^").concat(mo(a),"])+?")},"safePattern");l<t.length;){var v=p("CHAR"),L=p("NAME"),C=p("PATTERN");if(L||C){var $=v||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:$,suffix:"",pattern:C||b($),modifier:p("MODIFIER")||""});continue}var F=v||p("ESCAPED_CHAR");if(F){d+=F;continue}d&&(u.push(d),d="");var q=p("OPEN");if(q){var $=f(),A=p("NAME")||"",H=p("PATTERN")||"",V=f();m("CLOSE"),u.push({name:A||(H?c++:""),pattern:A&&!H?b($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(go,"parse");function la(n,e){return Vc(go(n,e),e)}i(la,"compile");function Vc(n,e){e===void 0&&(e={});var t=Wc(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,f=p.modifier==="?"||p.modifier==="*",P=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!P)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var v=o(m[b],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 m=="string"||typeof m=="number"){var v=o(String(m),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(!f){var L=P?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(Vc,"tokensToFunction");function mo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(mo,"escapeString");function Wc(n){return n&&n.sensitive?"":"i"}i(Wc,"flags");var Jc=we("zuplo:runtime"),ho=new TextEncoder,da={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"},Kc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=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 yo(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){Jc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},yo=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:f,allHeaders:P,singleEncode:b}){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 v,L;(!c||!l)&&([v,L]=Qc(this.url,this.headers)),this.service=c||v||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(F=>P||!Kc.includes(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(F=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").replace(/\s+/g," "))).join(`
|
|
65
|
+
`)}i(Ys,"messagesToMultilineText");function Xs(n){return typeof n=="string"?n:JSON.stringify(n)}i(Xs,"stringifyNonString");function eo(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"?Hr(n):"unknown"}i(eo,"stringifyNonStringToText");import{importPKCS8 as Dc,SignJWT as Mc}from"jose";async function Re(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(Re,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Mc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function ea(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return to("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(ea,"exchangeIDTokenForGcpWorkloadToken");async function ta({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ra(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ta,"generateServiceAccountIDToken");async function na(n,e,t){return to(n,{token:e,returnSecureToken:!0},t)}i(na,"exchangeFirebaseJwtForIdToken");async function vn(n,e,t){return to(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(vn,"exchangeGgpJwtForIdToken");async function to(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return ra(n,r,t)}i(to,"fetchTokenFromBody");async function ra(n,e,t){let r=await Re(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ra,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Dc(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 qc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},oa=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:qc[e.level],body:Ne(e.messages),attributes:t}},"unifiedFormatter");async function te(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await ia(y.instance,[r])}catch(r){console.error(r)}}i(te,"sendRemoteGlobalLog");async function ia(n,e){let t=oa(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});_e(r),await Z.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ia,"sendLogs");var Uc=i(n=>async e=>{e.length!==0&&await ia(n,e)},"dispatchFunction"),Cn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Cn||(Cn=new Y("unified-log-transport",1,Uc(e)))}log(e,t){Cn.enqueue(e),t.waitUntil(Cn.waitUntilFlushed())}};var no=class extends be{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Wt(this.options)}},Hc="https://logging.googleapis.com/v2/entries:write?alt=json",ro={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Wt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,h("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ne(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:ro[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=yt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(Hc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await te({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await te({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 An="gcp";function On(n){let e={allMessages:Ne(n.messages)},t="zuplo-production",r=yt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:ro[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 Jt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level](On(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ne(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var ao=class extends be{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Kt(this.options)}},oo="__ddtags",io="__ddattr",so=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),$c=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(so(r)):t.push(`${so(r)}:${so(o.toString())}`)}),t.join(",")},"formatTags"),Kt=class{static{i(this,"DataDogTransport")}constructor(e){h("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[oo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(f=>f[oo]!==void 0);a>-1&&(Object.assign(r,s[a][oo]),s.splice(a,1));let u={},c=t.custom[io];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(f=>f[io]!==void 0);l>-1&&(Object.assign(u,s[l][io]),s.splice(l,1));let d=Ne(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:yt(d),service:e.loggingId,ddtags:$c(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=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await te({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await te({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 Qt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===An){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 uo=we("zuplo:logging"),kn=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(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;uo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(mn);return s?o.push(new Qt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Bt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){uo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(mn);if(a&&a.captureUserLogs===!0?r.push(new Qt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Vt(e)),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(h("logging.google.legacy-initialization"),r.push(new Wt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){h("logging.datadog.legacy-initialization");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 He.forEach(u=>{u instanceof be&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Bt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){uo("Gateway.createRequestLoggers");let u=new Tn(r,o,s,a),c=new Gt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Gt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Ln=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var co=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r,this.urlPattern=new URLPattern({pathname:this.fullPath})}urlPattern;fullPath;config;executableHandler},_n=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof We||e instanceof ue))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new co(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Ln(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as Zc}from"node:async_hooks";var Nn={context:new Zc};var lo;function sa(n){lo=n}i(sa,"setGlobalZuploEventContext");function Ke(){if(lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return lo}i(Ke,"getGlobalZuploEventContext");function aa({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);gs.includes(o.toLowerCase())&&!fs.includes(r.toLowerCase())&&t.delete(r)}t.delete(ts)}else ms.forEach(r=>{t.delete(r)});return t}i(aa,"normalizeIncomingRequestHeaders");var Qe=we("zuplo:runtime"),he=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Qe("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Qe("Gateway.initialize"),!n.#e){let s=await kn.init(r),a=await e(),u={...a,corsPolicies:_s(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Qe("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[st,In,ye];setupRoutes=i(()=>{Qe("Gateway.setupRoutes");let e=this.routeData,t=new _n;if(e.routes.length===0)return Mr(t,this),zr(t,this),jr(t,this),Ns(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&(o==="zudoku"?(Js(t,this),Ks(t,this)):o==="legacy"&&(Ws(t,this),Vs(t,this))),Mr(t,this),zr(t,this),jr(t,this);for(let s of He)s instanceof ge&&s.registerRoutes(t,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 g(`Invalid state - No handler on route for path '${s.path}'`);let u=new de({processors:this.#r,handler:a,gateway:this}),c=new We(s);t.addRoute(c,u.execute)}),Ds(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Qe("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=at(o.cause);"stack"in a&&(a.stack=Xr(a.stack)),s={cause:a}}else{let a=at(o);"stack"in a&&(a.stack=Xr(a.stack)),s={cause:a}}return x.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t){let r=e.headers.get(gt)??e.headers.get(es)??crypto.randomUUID(),o=e.headers.get(nt);sa(t);let s=aa({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});s.set(gt,r);let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let C=new Headers(a.headers);C.set(gr,"true"),a=new Request(a,{headers:C,body:null})}let u=new URL(a.url),c=u.pathname,l=this.#n.lookup(c,a.method);if(!l)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${c}'`);let d={},{userRequestLogger:p,systemRequestLogger:m}=this.#t.createRequestLoggers(r,o,t,d,a,l.routeConfiguration),f=new Dn(e.headers),P=new ne(a,{params:l.params}),b=new Mn({logger:p,route:l.routeConfiguration,requestId:r,event:t,custom:d,incomingRequestProperties:f}),v=Nn.context.getStore();v&&(v.context=b);let L=l.routeConfiguration.raw();Fc.getActiveSpan()?.setAttributes({"http.route":b.route.path??b.route.pathPattern,"cloud.region":b.incomingRequestProperties.colo,[Ze.RoutePathPattern]:b.route.pathPattern,[Ze.RouteOperationId]:L.operationId,[Ze.RouteTrace]:L["x-zuplo-trace"],[Ze.RouteSystem]:ft(u)?!0:void 0}),Ee.initialize(b,P);try{if(Q.addLogger(b,m),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!ft(u):!u.pathname.startsWith("/__zuplo")){let q=await Es(P,b);if(q instanceof Response)return q;{let A=Ee.getContextExtensions(b);P=q,A.latestRequest=P}}ft(u)||p.debug(`Request received '${u.pathname}'`,{method:a.method,url:u.pathname,hostname:u.hostname,route:l.routeConfiguration.path});let C=l.executableHandler;jc(C,l,a),Qe("Gateway.handleRequest - call user handler");let $=await C(P,b);if(Qe("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if($.headers.get(gt)===null&&!$.webSocket){let q=new Headers($.headers);q.set(gt,r),F=new Response($.body,{status:$.status,statusText:$.statusText,headers:q,cf:$.cf})}else F=$;return F}catch(C){return C instanceof k?(p.error(C),m.warn(C)):m.error(C),await this.errorHandler(P,b,"Error executing handler",C)}}};function jc(n,e,t){if(Qe("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(jc,"checkHandler");var ua=i(async(n,e,t)=>{let r=he.instance.routeData.policies,o=jt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),ca=i(async(n,e,t,r)=>{let o=he.instance.routeData.policies,s=zt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var Dn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Rr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Pr)??void 0}get city(){return this.#e.get(fr)??this.#e.get(as)??void 0}get continent(){return this.#e.get(hr)??this.#e.get(us)??void 0}get country(){return this.#e.get(yr)??this.#e.get(cs)??void 0}get latitude(){return this.#e.get(wr)??this.#e.get(ds)??void 0}get longitude(){return this.#e.get(br)??this.#e.get(ls)??void 0}get colo(){return this.#e.get(Ir)??void 0}get postalCode(){return this.#e.get(is)??this.#e.get(Er)??void 0}get metroCode(){return this.#e.get(os)??this.#e.get(xr)??void 0}get region(){return this.#e.get(ns)??this.#e.get(Tr)??void 0}get regionCode(){return this.#e.get(rs)??this.#e.get(Sr)??void 0}get timezone(){return this.#e.get(ss)??this.#e.get(vr)??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}}},$t=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Zt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Ee=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 k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},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)=>ua(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>ca(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Ee.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Ee.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var zc="Error initializing gateway. Check your configuration for errors or contact support.",Bc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",po=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await Ss(this.runtimeInit)}catch(s){this.handleError(s,Bc,e)}return bs(i(async(s,a)=>{let u;try{u=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,zc,s)}let c={context:void 0};return Nn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function Gc(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(Gc,"lexer");function go(n,e){e===void 0&&(e={});for(var t=Gc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var T=p(j);if(T!==void 0)return T;var E=t[l],M=E.type,le=E.index;throw new TypeError("Unexpected ".concat(M," at ").concat(le,", expected ").concat(j))},"mustConsume"),f=i(function(){for(var j="",T;T=p("CHAR")||p("ESCAPED_CHAR");)j+=T;return j},"consumeText"),P=i(function(j){for(var T=0,E=a;T<E.length;T++){var M=E[T];if(j.indexOf(M)>-1)return!0}return!1},"isSafe"),b=i(function(j){var T=u[u.length-1],E=j||(T&&typeof T=="string"?T:"");if(T&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(T.name,'"'));return!E||P(E)?"[^".concat(mo(a),"]+?"):"(?:(?!".concat(mo(E),")[^").concat(mo(a),"])+?")},"safePattern");l<t.length;){var v=p("CHAR"),L=p("NAME"),C=p("PATTERN");if(L||C){var $=v||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:$,suffix:"",pattern:C||b($),modifier:p("MODIFIER")||""});continue}var F=v||p("ESCAPED_CHAR");if(F){d+=F;continue}d&&(u.push(d),d="");var q=p("OPEN");if(q){var $=f(),A=p("NAME")||"",H=p("PATTERN")||"",V=f();m("CLOSE"),u.push({name:A||(H?c++:""),pattern:A&&!H?b($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(go,"parse");function la(n,e){return Vc(go(n,e),e)}i(la,"compile");function Vc(n,e){e===void 0&&(e={});var t=Wc(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,f=p.modifier==="?"||p.modifier==="*",P=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!P)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var v=o(m[b],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 m=="string"||typeof m=="number"){var v=o(String(m),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(!f){var L=P?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(Vc,"tokensToFunction");function mo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(mo,"escapeString");function Wc(n){return n&&n.sensitive?"":"i"}i(Wc,"flags");var Jc=we("zuplo:runtime"),ho=new TextEncoder,da={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"},Kc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=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 yo(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){Jc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},yo=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:f,allHeaders:P,singleEncode:b}){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 v,L;(!c||!l)&&([v,L]=Qc(this.url,this.headers)),this.service=c||v||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(F=>P||!Kc.includes(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(F=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").replace(/\s+/g," "))).join(`
|
|
66
66
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!C.has("X-Amz-Expires")&&C.set("X-Amz-Expires","86400"),C.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),C.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),C.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ma(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([F])=>{if(!F)return!1;if(this.service==="s3"){if($.has(F))return!1;$.add(F)}return!0}).map(F=>F.map(q=>ma(encodeURIComponent(q)))).sort(([F,q],[A,H])=>F<A?-1:F>A?1:q<H?-1:q>H?1:0).map(F=>F.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 Yt("AWS4"+this.secretAccessKey,e),s=await Yt(o,this.region),a=await Yt(s,this.service);r=await Yt(a,"aws4_request"),this.cache.set(t,r)}return fo(await Yt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,fo(await pa(await this.canonicalString()))].join(`
|
|
67
67
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
68
68
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|