@zuplo/runtime 5.2041.0 → 5.2042.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.min.cjs +1 -1
- package/index.min.js +1 -1
- package/package.json +1 -1
package/index.min.cjs
CHANGED
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=zs(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>zs(encodeURIComponent(H)))).sort(([S,H],[f,R])=>S<f?-1:S>f?1:H<R?-1:H>R?1:0).map(S=>S.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await Dt("AWS4"+this.secretAccessKey,e),s=await Dt(o,this.region),a=await Dt(s,this.service);r=await Dt(a,"aws4_request"),this.cache.set(n,r)}return yo(await Dt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,yo(await js(await this.canonicalString()))].join(`
|
|
64
64
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
65
65
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
66
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new C("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=yo(await js(this.body||""))}return e}};async function Dt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?bo.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,bo.encode(e))}i(Dt,"hmac");async function js(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?bo.encode(t):t)}i(js,"hash");function yo(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(yo,"buf2hex");function zs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(zs,"encodeRfc3986");function Jl(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")n.startsWith("iot.")?s="execute-api":n.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Bs?[Bs[s],a]:[s,a]}i(Jl,"guessServiceRegion");function Kl(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Kl,"b64ToUint6");function Gs(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Kl(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Gs,"base64Decode");function Sn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(Sn,"uint6ToB64");function Ws(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(Sn(o>>>18&63),Sn(o>>>12&63),Sn(o>>>6&63),Sn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ws,"base64Encode");function lt(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(lt,"numberToString");function Yl(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=lt(Math.floor(n/60)),s=lt(n%60);return`${r}${o}${s}`}i(Yl,"getCLFOffset");function Ro(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=lt(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=lt(t.getHours()),a=lt(t.getMinutes()),u=lt(t.getSeconds()),c=Yl(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Ro,"toCLFDate");var Js=(0,Ks.debug)("zuplo:runtime"),Ql="X-Amzn-Trace-Id",Xl="x-amzn-errortype",Ys=[],ed=i(async(t,e,n)=>{let r=n;for await(let o of Ys)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),de=class extends C{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Ql)??void 0,this.errorType=n.get(Xl)??void 0}},Qs={addSendingAwsLambdaEventHook:t=>{Ys.push(t)}};async function Xs(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new ct({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Js(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await od(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=rd(t,e):I=await nd(t,e,{useAwsResourcePathStyle:u}),Js("Calling onSendingAwsLambdaEvent hook");let y=await ed(t,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return td(T)}catch(_){if(_ instanceof de){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(t,e,void 0,h)}throw _}}i(Xs,"awsLambdaHandler");async function td(t){let e;try{e=await t.json()}catch{throw new de("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new de(e.message,t.headers):new de(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new de(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new de(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new de(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new de(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new de("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new de("Response was set to base64 encoded but body was not a string",t.headers);r=Gs(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new de(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(td,"getResponse");async function nd(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Ro(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:sd(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(nd,"buildEventVersion1");function rd(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ro(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(rd,"buildEventVersion2");async function od(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&id(e,o)){let s=await t.arrayBuffer();n=Ws(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(od,"getBodyResult");function id(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(id,"matchesContentType");function sd(t,e=!1){if(!e)return t;let n=ho(t),r=Fs(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(sd,"getResourcePath");var ad=[502,503,504];async function dt(t,e){if(ad.includes(t.status)){let n=j.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(dt,"logBadGatewayResponses");var Po;function Ze(t){if(Po===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Po=n}return t.log[Po]}i(Ze,"getHandlerUserLogFunction");async function ea(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ud(s);if(!a.isValid)throw new b(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await M.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return v.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return dt(l,e),l}i(ea,"openApiSpecHandler");var ud=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function ta(t,e){let n=e.route.handler.options;if(!n.location)throw new b("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(ta,"redirectHandler");function cd(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(cd,"join");async function na(t,e){let n=Ze(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=cd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),dt(p,e),p}i(na,"urlForwardHandler");var ld=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function ra(t,e){let n=Ze(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?ld(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await M.fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),dt(d,e),d}i(ra,"urlRewriteHandler");async function oa(t,e){let n=w.instance,r=e.route.handler.options,o=Ze(e);if(!r||!r.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await ki(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let T in g.tunnelHeaders)p.set(T,g.tunnelHeaders[T])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(oa,"webSocketHandler");var Eo=i((t,e)=>t.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ia=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function sa(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ia(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(sa,"wireUpListeners");async function aa(t,e){let n=w.instance,r=e.route.handler.options,o=Ze(e);if(!r||!r.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new b("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let _=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${_}'`;throw new Error(h)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let y=r.policies&&r.policies.inbound?Eo(r.policies.inbound,"inbound"):[],T=r.policies&&r.policies.outbound?Eo(r.policies.outbound,"outbound"):[];return sa(m,I,t,e,y),sa(I,m,t,e,T),new Response(null,{status:101,webSocket:p})}i(aa,"webSocketPipelineHandler");var On=class extends X{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Io(this.options)}},Io=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ce(se(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new $("dyna-trace-log-transport",10,this.#i)};var Cn=class extends X{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new xo(this.options)}},To=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s,a){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function dd(t,e){return btoa(`${t}:${e}`)}i(dd,"createBasicDigest");var xo=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=dd(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=new To(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,message:Ce(se(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),this.#e>1&&o.values.push(["requestId",r.requestId]),o.values.push([r.nanoSecondEpoch,r.message])}),n};#u=async e=>{if(e.length===0)return;let n=this.#a(e);await M.fetch(this.#n,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new $("loki-log-transport",10,this.#u)};var An=class extends X{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new vo(this.options)}},vo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ce(se(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
66
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new C("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=yo(await js(this.body||""))}return e}};async function Dt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?bo.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,bo.encode(e))}i(Dt,"hmac");async function js(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?bo.encode(t):t)}i(js,"hash");function yo(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(yo,"buf2hex");function zs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(zs,"encodeRfc3986");function Jl(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")n.startsWith("iot.")?s="execute-api":n.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Bs?[Bs[s],a]:[s,a]}i(Jl,"guessServiceRegion");function Kl(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Kl,"b64ToUint6");function Gs(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Kl(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Gs,"base64Decode");function Sn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(Sn,"uint6ToB64");function Ws(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(Sn(o>>>18&63),Sn(o>>>12&63),Sn(o>>>6&63),Sn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ws,"base64Encode");function lt(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(lt,"numberToString");function Yl(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=lt(Math.floor(n/60)),s=lt(n%60);return`${r}${o}${s}`}i(Yl,"getCLFOffset");function Ro(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=lt(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=lt(t.getHours()),a=lt(t.getMinutes()),u=lt(t.getSeconds()),c=Yl(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Ro,"toCLFDate");var Js=(0,Ks.debug)("zuplo:runtime"),Ql="X-Amzn-Trace-Id",Xl="x-amzn-errortype",Ys=[],ed=i(async(t,e,n)=>{let r=n;for await(let o of Ys)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),de=class extends C{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Ql)??void 0,this.errorType=n.get(Xl)??void 0}},Qs={addSendingAwsLambdaEventHook:t=>{Ys.push(t)}};async function Xs(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new ct({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Js(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await od(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=rd(t,e):I=await nd(t,e,{useAwsResourcePathStyle:u}),Js("Calling onSendingAwsLambdaEvent hook");let y=await ed(t,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return td(T)}catch(_){if(_ instanceof de){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(t,e,void 0,h)}throw _}}i(Xs,"awsLambdaHandler");async function td(t){let e;try{e=await t.json()}catch{throw new de("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new de(e.message,t.headers):new de(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new de(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new de(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new de(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new de(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new de("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new de("Response was set to base64 encoded but body was not a string",t.headers);r=Gs(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new de(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(td,"getResponse");async function nd(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Ro(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:sd(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(nd,"buildEventVersion1");function rd(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ro(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(rd,"buildEventVersion2");async function od(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&id(e,o)){let s=await t.arrayBuffer();n=Ws(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(od,"getBodyResult");function id(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(id,"matchesContentType");function sd(t,e=!1){if(!e)return t;let n=ho(t),r=Fs(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(sd,"getResourcePath");var ad=[502,503,504];async function dt(t,e){if(ad.includes(t.status)){let n=j.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(dt,"logBadGatewayResponses");var Po;function Ze(t){if(Po===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Po=n}return t.log[Po]}i(Ze,"getHandlerUserLogFunction");async function ea(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ud(s);if(!a.isValid)throw new b(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await M.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return v.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return dt(l,e),l}i(ea,"openApiSpecHandler");var ud=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function ta(t,e){let n=e.route.handler.options;if(!n.location)throw new b("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(ta,"redirectHandler");function cd(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(cd,"join");async function na(t,e){let n=Ze(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=cd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),dt(p,e),p}i(na,"urlForwardHandler");var ld=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function ra(t,e){let n=Ze(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?ld(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await M.fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),dt(d,e),d}i(ra,"urlRewriteHandler");async function oa(t,e){let n=w.instance,r=e.route.handler.options,o=Ze(e);if(!r||!r.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await ki(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let T in g.tunnelHeaders)p.set(T,g.tunnelHeaders[T])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(oa,"webSocketHandler");var Eo=i((t,e)=>t.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ia=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function sa(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ia(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(sa,"wireUpListeners");async function aa(t,e){let n=w.instance,r=e.route.handler.options,o=Ze(e);if(!r||!r.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new b("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let _=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${_}'`;throw new Error(h)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let y=r.policies&&r.policies.inbound?Eo(r.policies.inbound,"inbound"):[],T=r.policies&&r.policies.outbound?Eo(r.policies.outbound,"outbound"):[];return sa(m,I,t,e,y),sa(I,m,t,e,T),new Response(null,{status:101,webSocket:p})}i(aa,"webSocketPipelineHandler");var On=class extends X{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Io(this.options)}},Io=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ce(se(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new $("dyna-trace-log-transport",10,this.#i)};var Cn=class extends X{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new xo(this.options)}},To=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s,a){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function dd(t,e){return btoa(`${t}:${e}`)}i(dd,"createBasicDigest");var xo=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=dd(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=new To(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Ce(se(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),n};#u=async e=>{if(e.length===0)return;let n=this.#a(e);await M.fetch(this.#n,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new $("loki-log-transport",10,this.#u)};var An=class extends X{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new vo(this.options)}},vo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ce(se(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
67
67
|
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await M.fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new $("sumo-logic-log-transport",10,this.#s)};var pd="d3a5b78f823648f5b1df4fe269d41172",_n=class extends X{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new So(this.options)}},So=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??pd}`)}catch{throw new b(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=_s(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=io(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let n=await M.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new $("vmware-log-insights-log-transport",10,this.#a)};var Ln=class extends X{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Oo(this.options)}},Oo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new $("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new ct({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Ce(se(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Co=new WeakMap,md={tags:[]},Nn=class extends Ue{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Ao(this.options)}static setContext(n,r){let o=Co.get(n);o||(o=md);let s=Object.assign({...o},r);Co.set(n,s)}},Ao=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new $("data-dog-metrics-transport",10,this.dispatchFunction,j.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Co.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await M.fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new _o(await r.text())}},_o=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Lo=new WeakMap,gd={dimensions:[]},kn=class extends Ue{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new No(this.options)}static setContext(n,r){let o=Lo.get(n);o||(o=gd);let s=Object.assign({...o},r);Lo.set(n,s)}},No=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new $("dynatrace-metrics-transport",10,this.dispatchFunction,j.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Lo.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
|
|
68
68
|
`),r=await M.fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ko(await r.text())}},ko=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Mn=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await M.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var Dn=class extends ve{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Mo(e,this.#e,this.#t)}},ua=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),fd={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Mo=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...fd};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new $("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?ua(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?ua(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(m=>{n.log.error(m)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Do=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},xe=class extends Do{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var hd="v1",yd=300;async function ca(t,e,n,r=yd,o){return await wd(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(ca,"constructEventAsync");function bd(t,e){return`${e.timestamp}.${t}`}i(bd,"makeHMACContent");async function wd(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Rd(t,e,hd),l=/\s/.test(n),d=await Td(bd(a,u),n);return Pd(a,s,u,d,r,c,l,o)}i(wd,"verifyHeaderAsync");function Rd(t,e,n){if(!t)throw new xe(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new xe(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Ed(a,n);if(!u||u.timestamp===-1)throw new xe(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new xe(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Rd,"parseEventDetails");function Pd(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(m=>Id(m,r)).length,l=`
|
|
69
69
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
package/index.min.js
CHANGED
|
@@ -64,7 +64,7 @@ var Ha=Object.create;var Mn=Object.defineProperty;var Za=Object.getOwnPropertyDe
|
|
|
64
64
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!h.has("X-Amz-Expires")&&h.set("X-Amz-Expires","86400"),h.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),h.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),h.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");y||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Zs(this.encodedPath);let P=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return!1;if(this.service==="s3"){if(P.has(S))return!1;P.add(S)}return!0}).map(S=>S.map(H=>Zs(encodeURIComponent(H)))).sort(([S,H],[f,R])=>S<f?-1:S>f?1:H<R?-1:H>R?1:0).map(S=>S.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await _t("AWS4"+this.secretAccessKey,e),s=await _t(o,this.region),a=await _t(s,this.service);r=await _t(a,"aws4_request"),this.cache.set(n,r)}return Vr(await _t(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Vr(await Hs(await this.canonicalString()))].join(`
|
|
65
65
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
66
66
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
67
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Vr(await Hs(this.body||""))}return e}};async function _t(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Gr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Gr.encode(e))}i(_t,"hmac");async function Hs(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Gr.encode(t):t)}i(Hs,"hash");function Vr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Vr,"buf2hex");function Zs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Zs,"encodeRfc3986");function Yc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")n.startsWith("iot.")?s="execute-api":n.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Us?[Us[s],a]:[s,a]}i(Yc,"guessServiceRegion");function Qc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Qc,"b64ToUint6");function $s(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Qc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i($s,"base64Decode");function gn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(gn,"uint6ToB64");function Fs(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(gn(o>>>18&63),gn(o>>>12&63),gn(o>>>6&63),gn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Fs,"base64Encode");function nt(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(nt,"numberToString");function Xc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=nt(Math.floor(n/60)),s=nt(n%60);return`${r}${o}${s}`}i(Xc,"getCLFOffset");function Jr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=nt(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=nt(t.getHours()),a=nt(t.getMinutes()),u=nt(t.getSeconds()),c=Xc(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Jr,"toCLFDate");var Bs=(0,js.debug)("zuplo:runtime"),el="X-Amzn-Trace-Id",tl="x-amzn-errortype",zs=[],nl=i(async(t,e,n)=>{let r=n;for await(let o of zs)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),de=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(el)??void 0,this.errorType=n.get(tl)??void 0}},rl={addSendingAwsLambdaEventHook:t=>{zs.push(t)}};async function ol(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new tt({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Bs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await ul(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=al(t,e):I=await sl(t,e,{useAwsResourcePathStyle:u}),Bs("Calling onSendingAwsLambdaEvent hook");let y=await nl(t,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return il(T)}catch(_){if(_ instanceof de){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(t,e,void 0,h)}throw _}}i(ol,"awsLambdaHandler");async function il(t){let e;try{e=await t.json()}catch{throw new de("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new de(e.message,t.headers):new de(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new de(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new de(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new de(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new de(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new de("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new de("Response was set to base64 encoded but body was not a string",t.headers);r=$s(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new de(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(il,"getResponse");async function sl(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Jr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ll(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(sl,"buildEventVersion1");function al(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Jr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(al,"buildEventVersion2");async function ul(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&cl(e,o)){let s=await t.arrayBuffer();n=Fs(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(ul,"getBodyResult");function cl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(cl,"matchesContentType");function ll(t,e=!1){if(!e)return t;let n=zr(t),r=Ds(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(ll,"getResourcePath");var dl=[502,503,504];async function rt(t,e){if(dl.includes(t.status)){let n=j.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(rt,"logBadGatewayResponses");var Kr;function Ue(t){if(Kr===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Kr=n}return t.log[Kr]}i(Ue,"getHandlerUserLogFunction");async function pl(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ml(s);if(!a.isValid)throw new b(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await M.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return v.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return rt(l,e),l}i(pl,"openApiSpecHandler");var ml=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function gl(t,e){let n=e.route.handler.options;if(!n.location)throw new b("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(gl,"redirectHandler");function fl(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(fl,"join");async function hl(t,e){let n=Ue(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=fl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),rt(p,e),p}i(hl,"urlForwardHandler");var yl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function bl(t,e){let n=Ue(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?yl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await M.fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),rt(d,e),d}i(bl,"urlRewriteHandler");async function wl(t,e){let n=w.instance,r=e.route.handler.options,o=Ue(e);if(!r||!r.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await vi(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let T in g.tunnelHeaders)p.set(T,g.tunnelHeaders[T])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(wl,"webSocketHandler");var Yr=i((t,e)=>t.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Vs=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Gs(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Vs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Gs,"wireUpListeners");async function Rl(t,e){let n=w.instance,r=e.route.handler.options,o=Ue(e);if(!r||!r.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new b("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let _=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${_}'`;throw new Error(h)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let y=r.policies&&r.policies.inbound?Yr(r.policies.inbound,"inbound"):[],T=r.policies&&r.policies.outbound?Yr(r.policies.outbound,"outbound"):[];return Gs(m,I,t,e,y),Gs(I,m,t,e,T),new Response(null,{status:101,webSocket:p})}i(Rl,"webSocketPipelineHandler");var Qr=class extends X{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(ie(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var eo=class extends X{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new no(this.options)}},to=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s,a){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Pl(t,e){return btoa(`${t}:${e}`)}i(Pl,"createBasicDigest");var no=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Pl(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=new to(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,message:Oe(ie(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),this.#e>1&&o.values.push(["requestId",r.requestId]),o.values.push([r.nanoSecondEpoch,r.message])}),n};#u=async e=>{if(e.length===0)return;let n=this.#a(e);await M.fetch(this.#n,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var ro=class extends X{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new oo(this.options)}},oo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
67
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Vr(await Hs(this.body||""))}return e}};async function _t(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Gr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Gr.encode(e))}i(_t,"hmac");async function Hs(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Gr.encode(t):t)}i(Hs,"hash");function Vr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Vr,"buf2hex");function Zs(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Zs,"encodeRfc3986");function Yc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")n.startsWith("iot.")?s="execute-api":n.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Us?[Us[s],a]:[s,a]}i(Yc,"guessServiceRegion");function Qc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Qc,"b64ToUint6");function $s(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Qc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i($s,"base64Decode");function gn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(gn,"uint6ToB64");function Fs(t){let e=2,n="",r=t.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(n+=String.fromCodePoint(gn(o>>>18&63),gn(o>>>12&63),gn(o>>>6&63),gn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}i(Fs,"base64Encode");function nt(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(nt,"numberToString");function Xc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=nt(Math.floor(n/60)),s=nt(n%60);return`${r}${o}${s}`}i(Xc,"getCLFOffset");function Jr(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=nt(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),s=nt(t.getHours()),a=nt(t.getMinutes()),u=nt(t.getSeconds()),c=Xc(t);return`${n}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Jr,"toCLFDate");var Bs=(0,js.debug)("zuplo:runtime"),el="X-Amzn-Trace-Id",tl="x-amzn-errortype",zs=[],nl=i(async(t,e,n)=>{let r=n;for await(let o of zs)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),de=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(el)??void 0,this.errorType=n.get(tl)??void 0}},rl={addSendingAwsLambdaEventHook:t=>{zs.push(t)}};async function ol(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new b("awsAccessKeyId is not set in the handler options");if(!r)throw new b("secretAccessKey is not set in the handler options");if(!o)throw new b("region is not set in the handler options");if(!s)throw new b("functionName is not set in the handler options");let l=new tt({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Bs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await ul(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,I;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?I=al(t,e):I=await sl(t,e,{useAwsResourcePathStyle:u}),Bs("Calling onSendingAwsLambdaEvent hook");let y=await nl(t,e,I);y.body=p,y.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(y)});try{return il(T)}catch(_){if(_ instanceof de){let h=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&_.traceId?{AMZN_TRACE_ID_HEADER:_.traceId}:void 0;return v.internalServerError(t,e,void 0,h)}throw _}}i(ol,"awsLambdaHandler");async function il(t){let e;try{e=await t.json()}catch{throw new de("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new de(e.message,t.headers):new de(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new de(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new de(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))n.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new de(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new de(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new de("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new de("Response was set to base64 encoded but body was not a string",t.headers);r=$s(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new de(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}i(il,"getResponse");async function sl(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Jr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:ll(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}i(sl,"buildEventVersion1");function al(t,e){let n={};t.headers.forEach((s,a)=>{n[a]=s});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Jr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(al,"buildEventVersion2");async function ul(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&cl(e,o)){let s=await t.arrayBuffer();n=Fs(new Uint8Array(s)),r=!0}else n=await t.clone().text();return[n,r]}i(ul,"getBodyResult");function cl(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}i(cl,"matchesContentType");function ll(t,e=!1){if(!e)return t;let n=zr(t),r=Ds(t),o={};return n.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(ll,"getResourcePath");var dl=[502,503,504];async function rt(t,e){if(dl.includes(t.status)){let n=j.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(rt,"logBadGatewayResponses");var Kr;function Ue(t){if(Kr===void 0){let n=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Kr=n}return t.log[Kr]}i(Ue,"getHandlerUserLogFunction");async function pl(t,e){let n=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new b("Open API Spec Handler must have 'openApiFilePath' specified");let a=ml(s);if(!a.isValid)throw new b(a.error);let u;w.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${n}${s.substring(1)}`;let c=await M.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return v.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return rt(l,e),l}i(pl,"openApiSpecHandler");var ml=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function gl(t,e){let n=e.route.handler.options;if(!n.location)throw new b("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}i(gl,"redirectHandler");function fl(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}i(fl,"join");async function hl(t,e){let n=Ue(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,s),c=fl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await M.fetch(l,{method:t.method,body:t.body,headers:t.headers}),m=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),rt(p,e),p}i(hl,"urlForwardHandler");var yl=i((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,s]of r.searchParams.entries())n.searchParams.append(o,s);return n.toString()},"addQuery");async function bl(t,e){let n=Ue(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?yl(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await M.fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),rt(d,e),d}i(bl,"urlRewriteHandler");async function wl(t,e){let n=w.instance,r=e.route.handler.options,o=Ue(e);if(!r||!r.rewritePattern)throw new b("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await vi(u),I=new URL(u);u=new URL(`${g.serviceBaseUrl}${I.pathname}${I.search}`).toString();for(let T in g.tunnelHeaders)p.set(T,g.tunnelHeaders[T])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let m=JSON.stringify({url:u});return new Response(m,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}i(wl,"webSocketHandler");var Yr=i((t,e)=>t.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new b(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Vs=i(async(t,e,n,r,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Gs(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Vs(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Gs,"wireUpListeners");async function Rl(t,e){let n=w.instance,r=e.route.handler.options,o=Ue(e);if(!r||!r.rewritePattern)throw new b("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return v.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new b("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new b("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await M.fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let _=await l.text(),h=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${_}'`;throw new Error(h)}let d=new WebSocketPair,[p,m]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let I=l.webSocket;I.accept(),m.accept();let y=r.policies&&r.policies.inbound?Yr(r.policies.inbound,"inbound"):[],T=r.policies&&r.policies.outbound?Yr(r.policies.outbound,"outbound"):[];return Gs(m,I,t,e,y),Gs(I,m,t,e,T),new Response(null,{status:101,webSocket:p})}i(Rl,"webSocketPipelineHandler");var Qr=class extends X{constructor(n){super();this.options=n}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{i(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(ie(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await M.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new F("dyna-trace-log-transport",10,this.#i)};var eo=class extends X{constructor(n){super();this.options=n}static{i(this,"LokiLoggingPlugin")}getTransport(){return new no(this.options)}},to=class{static{i(this,"LokiStream")}constructor(e,n,r,o,s,a){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Pl(t,e){return btoa(`${t}:${e}`)}i(Pl,"createBasicDigest");var no=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Pl(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=new to(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Oe(ie(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),n};#u=async e=>{if(e.length===0)return;let n=this.#a(e);await M.fetch(this.#n,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new F("loki-log-transport",10,this.#u)};var ro=class extends X{constructor(n){super();this.options=n}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new oo(this.options)}},oo=class{static{i(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Oe(ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
|
|
68
68
|
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await M.fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new F("sumo-logic-log-transport",10,this.#s)};var El="d3a5b78f823648f5b1df4fe269d41172",io=class extends X{constructor(n){super();this.options=n}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new so(this.options)}},so=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??El}`)}catch{throw new b(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=xs(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let u=Nr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let n=await M.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new F("vmware-log-insights-log-transport",10,this.#a)};var ao=class extends X{constructor(n){super();this.options=n}static{i(this,"AWSLoggingPlugin")}getTransport(){return new uo(this.options)}},uo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new F("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:s}){this.awsClient=new tt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=n,this.region=s,this.environmentType=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Oe(ie(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var co=new WeakMap,Il={tags:[]},lo=class extends ke{constructor(n){super();this.options=n}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new po(this.options)}static setContext(n,r){let o=co.get(n);o||(o=Il);let s=Object.assign({...o},r);co.set(n,s)}},po=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new F("data-dog-metrics-transport",10,this.dispatchFunction,j.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(co.get(n)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await M.fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new mo(await r.text())}},mo=class t extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var go=new WeakMap,Tl={dimensions:[]},fo=class extends ke{constructor(n){super();this.options=n}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ho(this.options)}static setContext(n,r){let o=go.get(n);o||(o=Tl);let s=Object.assign({...o},r);go.set(n,s)}},ho=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new F("dynatrace-metrics-transport",10,this.dispatchFunction,j.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(go.get(n)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
|
|
69
69
|
`),r=await M.fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new yo(await r.text())}},yo=class t extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var bo=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await M.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var wo=class extends xe{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Ro(e,this.#e,this.#t)}},Ws=i(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),xl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ro=class{static{i(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...xl};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new F("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?Ws(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Ws(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-s,c.user?.sub).catch(m=>{n.log.error(m)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Po=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Te=class extends Po{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var vl="v1",Sl=300;async function Js(t,e,n,r=Sl,o){return await Cl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}i(Js,"constructEventAsync");function Ol(t,e){return`${e.timestamp}.${t}`}i(Ol,"makeHMACContent");async function Cl(t,e,n,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Al(t,e,vl),l=/\s/.test(n),d=await kl(Ol(a,u),n);return _l(a,s,u,d,r,c,l,o)}i(Cl,"verifyHeaderAsync");function Al(t,e,n){if(!t)throw new Te(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),s=t instanceof Uint8Array?o.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Te(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Ll(a,n);if(!u||u.timestamp===-1)throw new Te(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Te(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Al,"parseEventDetails");function _l(t,e,n,r,o,s,a,u){let c=!!n.signatures.filter(m=>Nl(m,r)).length,l=`
|
|
70
70
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|