@zuplo/runtime 6.44.17 → 6.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/index.js +1 -1
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -66,7 +66,7 @@ import{a as y,b as Be,e as he,f as Ju,g as dr,h as pr,i as Ku,j as Qu}from"./chu
|
|
|
66
66
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Aa(this.encodedPath);let H=new Set;this.encodedSearch=[...this.url.searchParams].filter(([F])=>{if(!F)return!1;if(this.service==="s3"){if(H.has(F))return!1;H.add(F)}return!0}).map(F=>F.map(q=>Aa(encodeURIComponent(q)))).sort(([F,q],[A,$])=>F<A?-1:F>A?1:q<$?-1:q>$?1:0).map(F=>F.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await rn("AWS4"+this.secretAccessKey,e),s=await rn(o,this.region),a=await rn(s,this.service);r=await rn(a,"aws4_request"),this.cache.set(t,r)}return xo(await rn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,xo(await Sa(await this.canonicalString()))].join(`
|
|
67
67
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
68
68
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
69
|
-
`)}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 k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=xo(await Sa(this.body||""))}return e}};async function rn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?To.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,To.encode(e))}i(rn,"hmac");async function Sa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?To.encode(n):n)}i(Sa,"hash");function xo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(xo,"buf2hex");function Aa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Aa,"encodeRfc3986");function Rl(n,e){let{hostname:t,pathname:r}=n,o=t.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")t.startsWith("iot.")?s="execute-api":t.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 Ca?[Ca[s],a]:[s,a]}i(Rl,"guessServiceRegion");function Pl(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Pl,"b64ToUint6");function Oa(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.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|=Pl(t.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(Oa,"base64Decode");function Wn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Wn,"uint6ToB64");function ka(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(Wn(o>>>18&63),Wn(o>>>12&63),Wn(o>>>6&63),Wn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ka,"base64Encode");function Rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Rt,"numberToString");function Il(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Rt(Math.floor(t/60)),s=Rt(t%60);return`${r}${o}${s}`}i(Il,"getCLFOffset");function Co(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=Rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=Rt(n.getHours()),a=Rt(n.getMinutes()),u=Rt(n.getSeconds()),c=Il(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Co,"toCLFDate");var La=be("zuplo:runtime"),El="X-Amzn-Trace-Id",xl="x-amzn-errortype",_a=[],Tl=i(async(n,e,t)=>{let r=t;for await(let o of _a)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(El)??void 0,this.errorType=t.get(xl)??void 0}},vl={addSendingAwsLambdaEventHook:i(n=>{_a.push(n)},"addSendingAwsLambdaEventHook")};async function Cl(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new wt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(La(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await kl(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,I;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?I=Ol(n,e):I=await Al(n,e,{useAwsResourcePathStyle:u}),La("Calling onSendingAwsLambdaEvent hook");let b=await Tl(n,e,I);b.body=p,b.isBase64Encoded=m;let C=await l.fetch(d,{body:JSON.stringify(b)});try{return Sl(C)}catch(L){if(L instanceof Ce){let S=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&L.traceId?{AMZN_TRACE_ID_HEADER:L.traceId}:void 0;return x.internalServerError(n,e,void 0,S)}throw L}}i(Cl,"awsLambdaHandler");async function Sl(n){let e;try{e=await n.json()}catch{throw new Ce("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Ce(e.message,n.headers):new Ce(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ce(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Ce(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Ce(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Ce(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Ce("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ce("Response was set to base64 encoded but body was not a string",n.headers);r=Oa(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 Ce(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Sl,"getResponse");async function Al(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.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:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.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:Co(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:_l(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Al,"buildEventVersion1");function Ol(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Co(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Ol,"buildEventVersion2");async function kl(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Ll(e,o)){let s=await n.arrayBuffer();t=ka(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(kl,"getBodyResult");function Ll(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Ll,"matchesContentType");function _l(n,e=!1){if(!e)return n;let t=Eo(n),r=va(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(_l,"getResourcePath");var Nl=[502,503,504];async function Pt(n,e){if(Nl.includes(n.status)){let t=J.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Pt,"logBadGatewayResponses");var So;function Xe(n){if(So===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),So=t}return n.log[So]}i(Xe,"getHandlerUserLogFunction");async function Dl(n,e){f("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ml(s);if(!a.isValid)throw new g(a.error);let u=`${r}/${t}${s.substring(1)}`,c=await Z.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Pt(l,e),l}i(Dl,"openApiSpecHandler");var Ml=i(n=>n.startsWith("./")?n.startsWith("./config")?n.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 ql(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(ql,"redirectHandler");async function Ul(n){if(f("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new g("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),Z.fetch(e,{method:n.method,headers:t,body:n.body})}i(Ul,"zuploServiceProxy");function Hl(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(Hl,"join");async function $l(n,e){f("handler.url-forward");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(r.followRedirects&&f("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=Hl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),Pt(p,e),p}i($l,"urlForwardHandler");var Zl=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Fl(n,e){f("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Zl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Pt(d,e),d}i(Fl,"urlRewriteHandler");async function jl(n,e){f("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(jl,"webSocketHandler");var Ao=i((n,e)=>n.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 g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Na=i(async(n,e,t,r,o,s)=>{let a=n.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,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Da(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Na(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Da,"wireUpListeners");async function zl(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),L=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(L)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let h=c.webSocket;h.accept(),p.accept();let I=t.policies&&t.policies.inbound?Ao(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Ao(t.policies.outbound,"outbound"):[];return Da(p,h,n,e,I),Da(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(zl,"webSocketPipelineHandler");var Oo=class extends le{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new ko(this.options)}},ko=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"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.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("dyna-trace-log-transport",10,this.#s)};var Lo=class extends le{constructor(t){super();this.options=t}static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new _o(this.options)}},_o=class{static{i(this,"NewRelicTransport")}constructor(e){f("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:ve(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await Q({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("new-relic-log-transport",10,this.#a)};var No=class extends le{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Mo(this.options)}},Do=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Bl(n,e){return btoa(`${n}:${e}`)}i(Bl,"createBasicDigest");var Mo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=Bl(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new Do(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ve(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#u=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#c=i(async e=>{if(e.length===0)return;let t=this.#u(e);try{let r=await Z.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("loki-log-transport",10,this.#c)};var qo=class extends le{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Uo(this.options)}},Uo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(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.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
69
|
+
`)}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 k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=xo(await Sa(this.body||""))}return e}};async function rn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?To.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,To.encode(e))}i(rn,"hmac");async function Sa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?To.encode(n):n)}i(Sa,"hash");function xo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(xo,"buf2hex");function Aa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Aa,"encodeRfc3986");function Rl(n,e){let{hostname:t,pathname:r}=n,o=t.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")t.startsWith("iot.")?s="execute-api":t.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 Ca?[Ca[s],a]:[s,a]}i(Rl,"guessServiceRegion");function Pl(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Pl,"b64ToUint6");function Oa(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.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|=Pl(t.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(Oa,"base64Decode");function Wn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Wn,"uint6ToB64");function ka(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(Wn(o>>>18&63),Wn(o>>>12&63),Wn(o>>>6&63),Wn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ka,"base64Encode");function Rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Rt,"numberToString");function Il(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Rt(Math.floor(t/60)),s=Rt(t%60);return`${r}${o}${s}`}i(Il,"getCLFOffset");function Co(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=Rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=Rt(n.getHours()),a=Rt(n.getMinutes()),u=Rt(n.getSeconds()),c=Il(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Co,"toCLFDate");var La=be("zuplo:runtime"),El="X-Amzn-Trace-Id",xl="x-amzn-errortype",_a=[],Tl=i(async(n,e,t)=>{let r=t;for await(let o of _a)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(El)??void 0,this.errorType=t.get(xl)??void 0}},vl={addSendingAwsLambdaEventHook:i(n=>{_a.push(n)},"addSendingAwsLambdaEventHook")};async function Cl(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new wt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(La(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await kl(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,I;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?I=Ol(n,e):I=await Al(n,e,{useAwsResourcePathStyle:u}),La("Calling onSendingAwsLambdaEvent hook");let b=await Tl(n,e,I);b.body=p,b.isBase64Encoded=m;let C=await l.fetch(d,{body:JSON.stringify(b)});try{return Sl(C)}catch(L){if(L instanceof Ce){let S=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&L.traceId?{AMZN_TRACE_ID_HEADER:L.traceId}:void 0;return x.internalServerError(n,e,void 0,S)}throw L}}i(Cl,"awsLambdaHandler");async function Sl(n){let e;try{e=await n.json()}catch{throw new Ce("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Ce(e.message,n.headers):new Ce(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ce(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Ce(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Ce(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Ce(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Ce("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ce("Response was set to base64 encoded but body was not a string",n.headers);r=Oa(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 Ce(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(Sl,"getResponse");async function Al(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]||(a[l]=[]),a[l].push(d);let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.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:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.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:Co(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:_l(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Al,"buildEventVersion1");function Ol(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Co(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Ol,"buildEventVersion2");async function kl(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Ll(e,o)){let s=await n.arrayBuffer();t=ka(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(kl,"getBodyResult");function Ll(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Ll,"matchesContentType");function _l(n,e=!1){if(!e)return n;let t=Eo(n),r=va(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(_l,"getResourcePath");var Nl=[502,503,504];async function Pt(n,e){if(Nl.includes(n.status)){let t=J.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Pt,"logBadGatewayResponses");var So;function Xe(n){if(So===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),So=t}return n.log[So]}i(Xe,"getHandlerUserLogFunction");async function Dl(n,e){f("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ml(s);if(!a.isValid)throw new g(a.error);let u=`${r}/${t}${s.substring(1)}`,c=await Z.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Pt(l,e),l}i(Dl,"openApiSpecHandler");var Ml=i(n=>n.startsWith("./")?n.startsWith("./config")?n.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 ql(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(ql,"redirectHandler");async function Ul(n){if(f("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new g("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),Z.fetch(e,{method:n.method,headers:t,body:n.body})}i(Ul,"zuploServiceProxy");function Hl(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(Hl,"join");async function $l(n,e){f("handler.url-forward");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(r.followRedirects&&f("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=Hl(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),Pt(p,e),p}i($l,"urlForwardHandler");var Zl=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Fl(n,e){f("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Zl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Pt(d,e),d}i(Fl,"urlRewriteHandler");async function jl(n,e){f("handler.websocket");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(jl,"webSocketHandler");var Ao=i((n,e)=>n.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 g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Na=i(async(n,e,t,r,o,s)=>{let a=n.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,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Da(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Na(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Da,"wireUpListeners");async function zl(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(e);if(!t||!t.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),L=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(L)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let h=c.webSocket;h.accept(),p.accept();let I=t.policies&&t.policies.inbound?Ao(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Ao(t.policies.outbound,"outbound"):[];return Da(p,h,n,e,I),Da(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(zl,"webSocketPipelineHandler");var Oo=class extends le{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new ko(this.options)}},ko=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"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.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("dyna-trace-log-transport",10,this.#s)};var Lo=class extends le{constructor(t){super();this.options=t}static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new _o(this.options)}},_o=class{static{i(this,"NewRelicTransport")}constructor(e){f("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:ve(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await Q({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("new-relic-log-transport",10,this.#a)};var No=class extends le{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Mo(this.options)}},Do=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Bl(n,e){return btoa(`${n}:${e}`)}i(Bl,"createBasicDigest");var Mo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=Bl(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new Do(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ve(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#u=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#c=i(async e=>{if(e.length===0)return;let t=this.#u(e);try{let r=await Z.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("loki-log-transport",10,this.#c)};var qo=class extends le{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Uo(this.options)}},Uo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(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.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
70
70
|
`),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);try{let o=await Z.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await Q({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await Q({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("sumo-logic-log-transport",10,this.#a)};var Gl="d3a5b78f823648f5b1df4fe269d41172",Ho=class extends le{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new $o(this.options)}},$o=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Gl}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.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,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=da(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),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=co(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("vmware-log-insights-log-transport",10,this.#a)};var Zo=class extends le{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Fo(this.options)}},Fo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new K("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=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:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});r.ok||await Q({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s,fields:a}){f("logging.aws"),this.awsClient=new wt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=y.instance.loggingEnvironmentType,this.environmentStage=y.instance.loggingEnvironmentStage,this.environment=y.instance.deploymentName,this.fields=a??{}}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:ve(r),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var jo=class extends le{constructor(t){super();this.options=t}static{i(this,"SplunkLoggingPlugin")}getTransport(){return new zo(this.options)}},zo=class{static{i(this,"SplunkTransport")}constructor(e){f("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#c=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#u;#c;log(e,t){e.messages.forEach(r=>{let s={event:{message:ve(r),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#l=i(async e=>{if(e.length!==0)try{for(let t of e){let r={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#c&&(r["X-Splunk-Request-Channel"]=this.#c);let o=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:r});if(!o.ok){let s=await o.text();await Q({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${s}`]},o)}}}catch(t){await Q({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${t instanceof Error?t.message:String(t)}`]})}},"#dispatchFunction");batcher=new K("splunk-log-transport",10,this.#l)};var Bo=new WeakMap,Vl={tags:[]},Go=class extends qe{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Vo(this.options)}static setContext(t,r){let o=Bo.get(t);o||(o=Vl);let s=Object.assign({...o},r);Bo.set(t,s)}},Vo=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,t){this.#i===void 0&&(this.#i=new K("data-dog-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Bo.get(t)?.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}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await Z.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await Q({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await Q({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Wo=new WeakMap,Wl={dimensions:[]},Jo=class extends qe{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Ko(this.options)}static setContext(t,r){let o=Wo.get(t);o||(o=Wl);let s=Object.assign({...o},r);Wo.set(t,s)}},Ko=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,t){this.#r===void 0&&(this.#r=new K("dynatrace-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Wo.get(t)?.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}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=e.join(`
|
|
71
71
|
`),r=await Z.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await Q({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Qo=new WeakMap,Jl={attributes:{}},Yo=class extends qe{constructor(t){super();this.options=t;f("metrics.newrelic")}static{i(this,"NewRelicMetricsPlugin")}getTransport(){return new Xo(this.options)}static setContext(t,r){let o=Qo.get(t);o||(o=Jl);let s=Object.assign({...o},r);Qo.set(t,s)}},Xo=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,t){this.#i===void 0&&(this.#i=new K("new-relic-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o={...this.#r,...Qo.get(t)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let s=e.systemRouteName||e.routePath;o.path=s}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:r,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:r,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:r,attributes:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify([{metrics:e}]),r=await Z.fetch(this.#t,{method:"POST",body:t,headers:{"Content-Type":"application/json","Api-Key":this.#e}});r.ok||await Q({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${r.status} ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var ei=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await Z.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var ti=class extends ge{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new ni(e,this.#e,this.#t)}},Ma=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Kl={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ni=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Kl};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 K("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Ma(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Ma(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)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var at={None:0,Base64Encode:1},ri={None:0,JsonEscape:1},on=class{constructor(e,t=at.None){this.stream=e;this.flags=t;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getFlags(){return this.flags}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return null;let e=this.stream.getReader(),t=[];try{for(;;){let{done:u,value:c}=await e.read();if(u)break;t.push(c)}}finally{e.releaseLock()}let r=t.reduce((u,c)=>u+c.length,0),o=new Uint8Array(r),s=0;for(let u of t)o.set(u,s),s+=u.length;let a=new TextDecoder().decode(o);return this.flags&at.Base64Encode&&(a=btoa(a)),a}},Jn=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,t=>{switch(t){case"\\":return"\\\\";case'"':return'\\"';case`
|
|
72
72
|
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return t}})}async toString(){let t=this.getStream().getReader(),r=new TextDecoder,o="";for(;;){let{done:s,value:a}=await t.read();if(s)break;o+=r.decode(a,{stream:!0})}return o+=r.decode(),o}getStream(){let e=this.template,t=this.flags,r=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let s=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],u=0,c;for(;(c=s.exec(e))!==null;){if(c.index>u&&a.push({type:"literal",value:e.substring(u,c.index)}),c[1]){let m=o.get(c[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:c[0]})}else if(c[2]){let m=o.get(c[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:c[0]})}u=s.lastIndex}u<e.length&&a.push({type:"literal",value:e.substring(u)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=new Uint8Array(0);return new TransformStream({transform(I,b){let C=new Uint8Array(h.length+I.length);C.set(h),C.set(I,h.length);let L=C.length%3,S=C.length-L;if(S>0){let H=C.subarray(0,S),F="";for(let q=0;q<H.length;q+=3){let A=H[q],$=H[q+1],V=H[q+2],j=A<<16|$<<8|V;F+=m[j>>18&63],F+=m[j>>12&63],F+=m[j>>6&63],F+=m[j&63]}b.enqueue(F)}h=C.subarray(C.length-L)},flush(I){if(h.length>0){let b=h[0],C=h.length>1?h[1]:0,L=b<<16|C<<8,S="";S+=m[L>>18&63],S+=m[L>>12&63],S+=h.length===2?m[L>>6&63]:"=",S+="=",I.enqueue(S)}}})}i(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,h){let I=m.replace(/[\\\"\n\r\t\f\b]/g,b=>{switch(b){case"\\":return"\\\\";case'"':return'\\"';case`
|