UNPKG

serverless-aws-lambda

Version:

AWS Application Load Balancer and API Gateway - Lambda dev tool for Serverless. Allows Express synthax in handlers. Supports packaging, local invoking and offline ALB, APG, S3, SNS, SQS, DynamoDB Stream server mocking.

9 lines 104 kB
"use strict";var Hn=Object.create;var vt=Object.defineProperty,Wn=Object.defineProperties,$n=Object.getOwnPropertyDescriptor,Un=Object.getOwnPropertyDescriptors,Vn=Object.getOwnPropertyNames,Jt=Object.getOwnPropertySymbols,zn=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty,Cn=Object.prototype.propertyIsEnumerable;var Yt=r=>{throw TypeError(r)};var St=(r,e,t)=>e in r?vt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,L=(r,e)=>{for(var t in e||(e={}))Bt.call(e,t)&&St(r,t,e[t]);if(Jt)for(var t of Jt(e))Cn.call(e,t)&&St(r,t,e[t]);return r},de=(r,e)=>Wn(r,Un(e));var _n=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vn(e))!Bt.call(r,n)&&n!==t&&vt(r,n,{get:()=>e[n],enumerable:!(s=$n(e,n))||s.enumerable});return r};var U=(r,e,t)=>(t=r!=null?Hn(zn(r)):{},_n(e||!r||!r.__esModule?vt(t,"default",{value:r,enumerable:!0}):t,r));var l=(r,e,t)=>St(r,typeof e!="symbol"?e+"":e,t),At=(r,e,t)=>e.has(r)||Yt("Cannot "+t);var v=(r,e,t)=>(At(r,e,"read from private field"),t?t.call(r):e.get(r)),T=(r,e,t)=>e.has(r)?Yt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),$=(r,e,t,s)=>(At(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),I=(r,e,t)=>(At(r,e,"access private method"),t);var S=(r,e,t)=>new Promise((s,n)=>{var i=p=>{try{o(t.next(p))}catch(c){n(c)}},a=p=>{try{o(t.throw(p))}catch(c){n(c)}},o=p=>p.done?s(p.value):Promise.resolve(p.value).then(i,a);o((t=t.apply(r,e)).next())});var X=U(require("path"));var Qr=U(require("http")),Dt=require("os");var Ve=!1,Kn=r=>{Ve=r},Qn=()=>Ve,De=(r,e)=>{Ve&&console.log(`\x1B[${r}m${e}\x1B[0m`)},Jn=r=>console.log(`\x1B[31m${r}\x1B[0m`),Bn=r=>De("32",r),Yn=r=>De("33",r),Gn=r=>De("36",r),Zn=r=>De("90",r),Xn=r=>De("94",r),es=r=>Ve?console.log(r):void 0,w={GREEN:Bn,YELLOW:Yn,CYAN:Gn,BR_BLUE:Xn,RED:Jn,GREY:Zn,setDebug:Kn,getDebug:Qn,info:es};var ts=["@invoke","@url"],wt=r=>w.YELLOW(`Invalid Request Headers or query string for ${r}`),Oe,be,ze,H=class H{constructor(e){T(this,be);l(this,"debug",!1);this.debug=e.debug}static parseNameFromUrl(e){let t=e.split("/"),s=ts.includes(t[1])?t[2]:t[3];if(s=decodeURIComponent(s),s.includes(":function:")){let n=s.split(":function:");s=n[n.length-1]}if(s.includes(":")){let n=s.split(":");n.length==2&&(s=n[0])}return s}static getHandlerByName(e){if(!e)return;let t=H.parseNameFromUrl(e);return H.handlers.find(s=>s.name==t||s.outName==t)}addHandler(e){let t=H.handlers.findIndex(s=>s.name==e.name&&s.esOutputPath==e.esOutputPath);t==-1?(H.handlers.push(e),e.endpoints.length?e.endpoints.forEach(s=>{let n=s.kind=="alb"?"36":"35";s.paths.forEach(i=>{I(this,be,ze).call(this,s.methods.join(" "),i,n)})}):I(this,be,ze).call(this,"ANY",`/@invoke/${e.name}`),e.url&&I(this,be,ze).call(this,"ANY",`/@url/${e.name}`,"34")):H.handlers[t].runtime.startsWith("n")&&(H.handlers[t].clear(),H.handlers[t]=e)}};Oe=new WeakMap,be=new WeakSet,ze=function(e,t,s="90"){let n=`${e} http://localhost:${H.PORT}${t}`;console.log(`\x1B[${s}m${n}\x1B[0m`)},l(H,"handlers",[]),l(H,"PORT",0),l(H,"ip","127.0.0.1"),T(H,Oe,(e,t)=>{let s=[],n=t.toString();return e.forEach(i=>{let a=i.some(({Key:o,Value:p})=>{if(o){let c=t[o.toLowerCase()];return p?c?c.includes(p.toLowerCase()):!1:(w.RED("alb conditions query must have 'Value' when 'Key' is specified"),!1)}else if(p)return n==p.toLowerCase()});s.push(a)}),s.every(i=>i===!0)}),l(H,"findHandler",({method:e,path:t,kind:s,headers:n,query:i})=>{let a,o=s==null?void 0:s.toLowerCase();if(H.handlers.find(c=>c.endpoints.filter(d=>s?d.kind==o:d).find(d=>{var f;if(d.kind=="apg"){let h=d.paths.includes(t)&&(d.methods.includes("ANY")||d.methods.includes(e));if(h){let y=[h];d.headers&&y.push(d.headers.every(g=>g in n)),d.querystrings&&y.push(d.querystrings.every(g=>g in i));let b=y.every(g=>g===!0);return b?a={event:d,handler:c}:wt(c.name),b}}let m=d.paths.includes(t)&&(d.methods.includes("ANY")||d.methods.includes(e));if(m){let u=[m];if(d.query&&u.push(v(f=H,Oe).call(f,d.query,i)),d.header){let y=d.header.every(b=>n[b.name.toLowerCase()]&&b.values.some(g=>n[b.name.toLowerCase()].find(x=>x==g)));u.push(y)}let h=u.every(y=>y===!0);return h?a={event:d,handler:c}:wt(c.name),h}})))return a;{let c=t.split("/").filter(Boolean).length;if(H.handlers.find(m=>m.endpoints.filter(f=>s?f.kind==o:f).find(f=>{var y;let h=f.paths.find((b,g)=>{let x=t.match(f.pathsRegex[g]);return f.kind=="alb"||b.includes("+")||b=="/*"?x:x&&b.split("/").filter(Boolean).length==c})&&(f.methods.includes("ANY")||f.methods.includes(e));if(h){let b=[h];if(f.kind=="alb"){if(f.query&&b.push(v(y=H,Oe).call(y,f.query,i)),f.header){let x=f.header.every(A=>n[A.name.toLowerCase()]&&A.values.some(k=>n[A.name.toLowerCase()].find(N=>N==k)));b.push(x)}}else f.headers&&b.push(f.headers.every(x=>x in n)),f.querystrings&&b.push(f.querystrings.every(x=>x in i));let g=b.every(x=>x===!0);return g?a={event:f,handler:m}:wt(m.name),g}})))return a}});var F=H;var nr=require("crypto");var Gt=U(require("http")),rs=r=>{switch(r.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${r.name}/`;default:break}},Zt=(r,e)=>{let t=rs(e);if(!t)return;let s={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Gt.default.request(`http://localhost:${r}/${t}`,{method:"POST",headers:s})},Xt=({event:r,payload:e,requestId:t,lambdaName:s,success:n})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:t,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${s}:$LATEST`,condition:n?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:r,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return n||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},ns=({topicName:r,event:e,payload:t,requestId:s,success:n,lambdaName:i})=>{let a="";if(n)a=Xt({event:e,payload:t,requestId:s,success:n,lambdaName:i});else if(typeof e=="string")a=e;else try{a=JSON.stringify(e)}catch(p){console.log(p)}let o={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${r}`,Message:a,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return n||(o.MessageAttributes={RequestID:{Type:"String",Value:s},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:t.errorMessage}}),JSON.stringify(o)},ss=({destination:r,event:e,payload:t,requestId:s,lambdaName:n,success:i})=>{let a=new URLSearchParams;a.append("QueueUrl",r.name),a.append("Action","SendMessage");let o=e;try{o=JSON.stringify(o)}catch(p){}return a.append("MessageBody",o),i||(a.append("MessageAttribute.1.Name","RequestID"),a.append("MessageAttribute.1.Value.StringValue",s),a.append("MessageAttribute.1.Value.DataType","String"),a.append("MessageAttribute.1.Name","ErrorCode"),a.append("MessageAttribute.1.Value.StringValue","200"),a.append("MessageAttribute.1.Value.DataType","Number"),a.append("MessageAttribute.1.Name","ErrorMessage"),a.append("MessageAttribute.1.Value.StringValue",t.errorMessage),a.append("MessageAttribute.1.Value.DataType","String")),a.toString()},er=({destination:r,event:e,payload:t,requestId:s,lambdaName:n,success:i})=>{switch(r.kind){case"sns":return ns({topicName:r.name,event:e,payload:t,requestId:s,success:i,lambdaName:n});case"lambda":return Xt({event:e,payload:t,requestId:s,lambdaName:n,success:i});case"sqs":return ss({destination:r,event:e,payload:t,requestId:s,lambdaName:n,success:i});default:return""}},xt=({destination:r,LOCAL_PORT:e,event:t,payload:s,requestId:n,lambdaName:i})=>{try{let a=Zt(e,r);if(!a)return;a.end(er({destination:r,event:t,payload:s,requestId:n,lambdaName:i,success:!1}))}catch(a){}},tr=({destination:r,LOCAL_PORT:e,event:t,payload:s,requestId:n,lambdaName:i})=>{try{let a=Zt(e,r);if(!a)return;a.end(er({destination:r,event:t,payload:s,requestId:n,lambdaName:i,success:!0}))}catch(a){}};var is=18*60*1e3,as=new Set(["async","ddb","kinesis","s3","sns","sqs"]),rr=r=>typeof(r==null?void 0:r.kind)=="string"?as.has(r.kind)||r.async:!1,ve,Ce,_e,Ke,Se=class Se{constructor({name:e,outName:t,online:s,endpoints:n,runtime:i,timeout:a,memorySize:o,environment:p,handlerPath:c,handlerName:d,esEntryPoint:m,esOutputPath:f,entryPoint:u,s3:h,sns:y,sqs:b,ddb:g,kinesis:x,url:A,documentDb:k,invokeSub:N,invokeSuccessSub:E,invokeErrorSub:P,onError:M,onSuccess:q,onFailure:Z,runner:ee}){l(this,"name");l(this,"outName");l(this,"online");l(this,"endpoints");l(this,"runtime");l(this,"s3");l(this,"sns");l(this,"sqs");l(this,"ddb");l(this,"kinesis");l(this,"documentDb");l(this,"url");l(this,"timeout");l(this,"memorySize");l(this,"environment");l(this,"handlerPath");l(this,"handlerName");l(this,"esEntryPoint");l(this,"esOutputPath");l(this,"entryPoint");l(this,"onError");l(this,"onSuccess");l(this,"onFailure");l(this,"invokeSub");l(this,"invokeSuccessSub");l(this,"invokeErrorSub");T(this,ve);l(this,"runner");l(this,"clear",()=>{clearTimeout(v(this,ve)),this.runner.unmount()});T(this,Ce,()=>{clearTimeout(v(this,ve)),$(this,ve,setTimeout(()=>{this.runner.unmount(!0)},is))});T(this,_e,(e,t,s)=>{var c,d,m,f;let n=(d=(c=t==null?void 0:t.httpMethod)!=null?c:t==null?void 0:t.method)!=null?d:"",i=(f=(m=t==null?void 0:t.path)!=null?m:t==null?void 0:t.rawPath)!=null?f:"";i&&(i=decodeURI(i));let a=`${n} ${i}`,o=new Date;w.CYAN(`${o.toLocaleDateString()} ${o.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${a}`),w.GREY(this.entryPoint);let p="";return typeof(s==null?void 0:s.kind)=="string"&&(p=` (${s.kind.toUpperCase()})`),w.YELLOW(`input payload${p}`),w.info(t),process.hrtime()});this.name=e,this.outName=t,this.online=s,this.endpoints=n,this.runtime=i,this.s3=h,this.sns=y,this.sqs=b,this.ddb=g,this.kinesis=x,this.url=A,this.documentDb=k,this.timeout=a,this.memorySize=o,this.environment=p,this.handlerPath=c,this.handlerName=d,this.esEntryPoint=m,this.esOutputPath=f,this.entryPoint=u,this.invokeSub=N,this.invokeSuccessSub=E,this.invokeErrorSub=P,this.onError=M,this.onSuccess=q,this.onFailure=Z,this.runner=ee}handleErrorDestination(e,t,s,n){if(this.runner.onComplete(n),console.error(s),this.invokeErrorSub.forEach(i=>{try{i(e,s,t)}catch(a){}}),rr(t)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:s,requestId:n,lambdaName:this.outName};this.onError&&xt(de(L({},i),{destination:this.onError})),this.onFailure&&xt(de(L({},i),{destination:this.onFailure}))}}handleSuccessDestination(e,t,s,n){this.runner.onComplete(n),this.onSuccess&&rr(t)&&tr({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:s,requestId:n,lambdaName:this.outName}),this.invokeSuccessSub.forEach(i=>{try{i(e,s,t)}catch(a){}})}invoke(e,t,s,n){return S(this,null,function*(){var o;this.runner.isMounted||(w.BR_BLUE(`\u2744\uFE0F Cold start '${this.outName}'`),yield this.runner.mount());let i=(0,nr.randomUUID)();this.invokeSub.forEach(p=>{try{let c=p(e,t);c&&typeof c.then!="function"&&(e=c)}catch(c){}});let a=v(this,_e).call(this,i,e,t);try{let p=yield new Promise((c,d)=>S(this,null,function*(){let m;Se.ENABLE_TIMEOUT&&(m=setTimeout(()=>{n==null||n.destroy(),this.runner.onComplete(i,!0),w.RED(`'${this.outName}' | ${i}: Request failed`),d({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let f=yield this.runner.invoke({event:e,awsRequestId:i,info:t,clientContext:s,response:n});c(f)}catch(f){d(f)}finally{clearTimeout(m)}}));return this.handleSuccessDestination(e,t,p,i),p}catch(p){throw this.handleErrorDestination(e,t,p,i),this.runner.unmount(!0),p}finally{v(this,Ce).call(this),v(o=Se,Ke).call(o,a,this.name)}})}};ve=new WeakMap,Ce=new WeakMap,_e=new WeakMap,Ke=new WeakMap,l(Se,"ENABLE_TIMEOUT",!0),T(Se,Ke,(e,t)=>{let s=process.hrtime(e),n=`${s[0]},${s[1]}s`,i=`\u231B\uFE0F '${t}' execution time: ${n}`;setTimeout(()=>{w.YELLOW(i)},400)});var je=Se;var Jr=U(require("inspector"));var sr="<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>",ir="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",ar="<html><head><title>400 Request Header Or Cookie Too Large</title></head><body><center><h1>400 Bad Request</h1></center><center>Request Header Or Cookie Too Large</center></body></html>",or="<html><head><title>400 Bad Request</title></head><body><center><h1>400 Bad Request</h1></center></body></html>";var Br=U(require("serve-static")),Ot=require("crypto");var cr="application/vnd.awslambda.http-integration-response",Ae,C,Et,lr,pr,dr,Qe,me=class me{constructor(e){T(this,C);l(this,"buffer");l(this,"_isHttpIntegrationResponse");l(this,"_metaDelimiter");l(this,"_endDelimiter");l(this,"_ct");l(this,"_isStreamResponse",!0);T(this,Ae);this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,$(this,Ae,e)}setHeader(e,t){this._isHttpIntegrationResponse=!this.buffer&&t==cr&&(!this._ct||this._ct==cr),this._ct=t}write(e,t){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),I(this,C,Et).call(this,e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&I(this,C,Et).call(this,e)}destroy(){}getParsedResponse(){if(!v(this,Ae))return;let e=v(this,Ae).kind;if(e=="alb")return I(this,C,lr).call(this);if(e=="url")return I(this,C,dr).call(this);if(e=="apg")return I(this,C,pr).call(this)}};Ae=new WeakMap,C=new WeakSet,Et=function(e){this.buffer=typeof this.buffer=="undefined"?e:Buffer.concat([this.buffer,e])},lr=function(){let e=this._isHttpIntegrationResponse?me.splitMessage(this.buffer):this.buffer,t;return e&&(t=I(this,C,Qe).call(this,e)),t},pr=function(){if(this._isHttpIntegrationResponse)return w.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":R.contentType.json},body:R.httpErrMsg};if(this.buffer)return I(this,C,Qe).call(this,this.buffer)},dr=function(){let e=me.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),t;return e&&(t=I(this,C,Qe).call(this,e)),t},Qe=function(e){let t=me.codec.decode(e);if(typeof t=="string")try{t=JSON.parse(t)}catch(s){}return t},l(me,"codec",new TextDecoder),l(me,"splitMessage",(e,t)=>{if(!e)return;let s=Array.from(e.values()),n=null;if(t)n=t;else for(let i=0;i<s.length;i++)if(s[i]===0&&[s[i+1],s[i+2],s[i+3],s[i+4],s[i+5],s[i+6],s[i+7]].every(p=>p===0)){n=i;break}if(n)return new Uint8Array(s.slice(0,n))});var _=me;var ur=require("crypto");var os=["GET","HEAD","POST","PUT","DELETE","PATCH"],cs=JSON.stringify({Message:null}),Je=r=>{if(r)try{let e=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(e)}catch(e){return new Error("InvalidRequestContentException")}},fr=(r,e)=>{if(!os.includes(e))return r.statusCode=403,r.setHeader("Content-Type","application/json"),r.end(cs),!0},ae=(r,e)=>S(void 0,null,function*(){let t;return r.on("data",n=>{t=typeof t=="undefined"?n:Buffer.concat([t,n])}),yield new Promise(n=>{r.on("end",()=>S(void 0,null,function*(){n(t?t.toString(e?"base64":"utf-8"):void 0)}))})}),Be=r=>{let e;try{e=JSON.parse(r)}catch(t){e&&e.length?e=t:e={}}return e},Ye=r=>r instanceof _,hr=r=>{let e,t=Buffer.from(r).toString();try{e=JSON.parse(t)}catch(s){e=t}return e},we=r=>{let e=(0,ur.randomUUID)();return r.setHeader("x-amzn-RequestId",e),e},Ge=r=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${r}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Ze=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),Xe=r=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:region:000000000000:function:${r}`}),et=r=>{r.writableFinished||(r.statusCode=502,r.headersSent||r.setHeader("Content-Type","application/json"),r.end("Internal Server Error"))},yr=r=>r.byteLength==8&&Array.from(r.values()).every(e=>e===0);var mr=new Error(ar),ls={alb:65536,apg:10240,url:10240},ps=16376,gr=(r,e)=>{if(!r.host)throw new Error(or);let t=0,s=ls[e],n=Object.entries(r);if(e=="alb"?n.forEach(i=>{let[a,o]=i;if(o=="x-mock-type")return;let p=a.length+o.length;if(p>ps)throw mr;t=t+p}):n.forEach(i=>{let[a,o]=i;o!="x-mock-type"&&(t=t+a.length+o.length)}),t>s)throw mr},br=r=>r.charAt(0).toUpperCase()+r.slice(1);var O=class O{static getApiGV1Headers(e,t){let{rawHeaders:s}=e,n,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(O.port)};for(let c=0;c<s.length;){let d=s[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let f=s[c+1];i[d]=f,m=="x-api-key"&&(n=f),c=c+2}let a={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))a[c]=i[c];let o={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(O.port)]};for(let c=0;c<s.length;){let d=s[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let f=s[c+1];o[d]?o[d].push(f):o[d]=[f],c=c+2}let p={};for(let c of Object.keys(o).sort((d,m)=>d.localeCompare(m)))p[c]=o[c];return{headers:a,multiValueHeaders:p,apiKey:n}}static getCustomHeaders(e,t){let{headers:s}=e;return delete s["x-mock-type"],delete s.connection,L({"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(O.port)},s)}static getPathParameters(e,t){let s=e.paths[0].split("/"),n=t.pathname.split("/"),i={};return s.forEach((a,o)=>{a.startsWith("{")&&a.endsWith("}")&&!a.endsWith("+}")&&(i[a.slice(1,-1)]=n[o])}),i}};l(O,"apiId",""),l(O,"accountId",""),l(O,"port",3e3),l(O,"serve"),l(O,"contentType",{json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"}),l(O,"keepAlive",["Connection","keep-alive"]),l(O,"dummyHost","http://localhost:3003"),l(O,"httpErrMsg",'{"message":"Internal Server Error"}'),l(O,"apigJsonParseErrMsg",'{"message":"[Unknown error parsing request body]"}'),l(O,"apigForbiddenErrMsg",'{"message":"Forbidden"}'),l(O,"amzMsgNull",'{"message":null}'),l(O,"apgTimeoutMsg",'{"message": "Endpoint request timed out"}'),l(O,"unavailable",'{"message":"Service Unavailable"}'),l(O,"timeoutRegex",/after.\d+.*seconds/),l(O,"apgRequestTimeout",30),l(O,"normalizeHeaderKey",e=>e.toLowerCase().split("-").map(br).join("-")),l(O,"getMultiValueHeaders",e=>{let t={},s=e.filter((i,a)=>a%2==0).map(i=>i.toLowerCase()),n=e.filter((i,a)=>a%2!==0);return s.forEach((i,a)=>{i!="x-mock-type"&&(t[i]?t[i].push(n[a]):t[i]=[n[a]])}),t}),l(O,"getIsBase64Encoded",e=>{let t=e["content-type"];return e["content-encoding"]||!t?!0:!(t.startsWith("application/json")||t.startsWith("application/xml")||t.startsWith("application/javascript")||t.startsWith("text/"))}),l(O,"knownHeaders",["accept","accept-encoding","user-agent","host","via","content-length"]),l(O,"normalizeSearchParams",(e,t)=>{let s={};Array.from(e.keys()).forEach(a=>{let o=e.getAll(a).map(c=>c.toLowerCase()),p=a.toLowerCase();o?s[p]?s[p].push(...o):s[p]=o:s[p]||(s[p]=void 0)});let n="",i=t.indexOf("?");return i!=-1&&(n=t.slice(i+1)),s.toString=()=>n,s}),l(O,"getMultiValueQueryStringParameters",e=>{let t={};e.delete("x_mock_type");for(let s of Array.from(new Set(e.keys())))t[s]=e.getAll(s).map(encodeURI);return t}),l(O,"isEndpointTimeoutError",e=>{var s;if(!e)return;let t=(s=e.match(O.timeoutRegex))==null?void 0:s[0];if(t){let n=t.split(" ")[1];if(!isNaN(n))return Number(n)>=O.apgRequestTimeout}});var R=O;var ue,xe,Sr,vr,K=class K extends R{constructor({res:t,req:s,body:n,mockEvent:i,multiValueHeaders:a,isBase64Encoded:o,lambdaName:p}){var c;super();l(this,"res");l(this,"payload");l(this,"mockEvent");l(this,"returnError",()=>this.res.writableFinished?!0:(this.res.shouldKeepAlive=!1,this.res.writeHead(502,[["Server","awselb/2.0"],["Date",new Date().toUTCString()],["Content-Type","text/html"],["Content-Length","110"],K.keepAlive]),this.res.end(sr)));l(this,"sendResponse",t=>{let s=[["Server","awselb/2.0"],["Date",new Date().toUTCString()]],n=[],i=200,a;if(!t||typeof t.statusCode!="number")throw w.RED(`Valid ALB Lambda response must be an object which includes a valid 'statusCode' number. Received:`),console.log(t),v(K,ue);i=t.statusCode;let{statusDescription:o}=t;if(typeof o=="string"){let u=o.split(" ");if(isNaN(u[0]))w.RED("statusDescription must start with a statusCode number followed by a space + status description text"),w.YELLOW("example: '200 Found'");else{let h=u.slice(1).join(" ");h.length&&(a=h)}}this.mockEvent.multiValueHeaders?t.multiValueHeaders?Object.keys(t.multiValueHeaders).filter(h=>h!=="Server"&&h!=="Date").forEach(h=>{if(Array.isArray(t.multiValueHeaders[h]))n.push([h,t.multiValueHeaders[h]]);else throw w.RED(`multiValueHeaders (${h}) values must be an array`),w.YELLOW("example:"),w.GREEN(`'${h}': ['some/value']`),v(K,ue)}):t.headers&&w.YELLOW("An ALB Lambda with 'multiValueHeaders enabled' must return 'multiValueHeaders' instead of 'headers'"):typeof t.headers=="object"&&!Array.isArray(t.headers)?Object.keys(t.headers).filter(h=>h!=="Server"&&h!=="Date").forEach(h=>{let y=typeof t.headers[h];if(y=="string")n.push([h,t.headers[h]]);else throw w.RED(`response headers (${h}) value must be typeof string. Received: '${y}'`),new Error}):t.multiValueHeaders&&w.YELLOW("Skipping 'multiValueHeaders' as it is not enabled for you target group in serverless.yml");let p=typeof t.body;if(p!="undefined"&&p!="string")throw w.RED(`response 'body' must be a string. Receievd ${p}`),v(K,ue);let c=t.body;if(c&&t.isBase64Encoded){let u=Buffer.from(c,"base64").toString();if(Buffer.from(u).toString("base64")!=c)throw w.RED("response body is not properly base64 encoded"),v(K,ue);c=u}let d=n.findIndex(u=>u[0].toLowerCase()=="content-type");d==-1?s.push(["Content-Type",K.contentType.octet]):(s.push(["Content-Type",n[d][1]]),n.splice(d,1));let m=n.findIndex(u=>u[0].toLowerCase()=="content-length"),f=c?String(Buffer.from(c).byteLength):"0";m!=-1&&n.splice(m,1),s.push(["Content-Length",f],K.keepAlive,...n),this.res.shouldKeepAlive=!1,a?this.res.writeHead(i,a,s):this.res.writeHead(i,s),this.res.end(c)});this.res=t,this.mockEvent=i,this.payload=I(c=K,xe,Sr).call(c,{req:s,mockEvent:i,multiValueHeaders:a,isBase64Encoded:o,body:n,lambdaName:p})}};ue=new WeakMap,xe=new WeakSet,Sr=function({req:t,mockEvent:s,multiValueHeaders:n,isBase64Encoded:i,body:a,lambdaName:o}){var u;let{method:p,headers:c,url:d}=t,m=new URL(d,K.dummyHost);m.searchParams.delete("x_mock_type");let f={requestContext:{elb:{targetGroupArn:`arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/${o}-tg/49e9d65c45c6791a`}},httpMethod:p,path:m.pathname,isBase64Encoded:a?i:!1,body:a!=null?a:""};return s.multiValueHeaders?(f.multiValueHeaders=L({"x-forwarded-for":[String(t.socket.remoteAddress)],"x-forwarded-proto":["http"],"x-forwarded-port":[String(R.port)]},n),f.multiValueQueryStringParameters=R.getMultiValueQueryStringParameters(m.searchParams)):(f.headers=L({"x-forwarded-for":t.socket.remoteAddress,"x-forwarded-proto":"http","x-forwarded-port":String(R.port)},c),f.queryStringParameters=I(u=K,xe,vr).call(u,d),f.headers["x-mock-type"]&&delete f.headers["x-mock-type"]),f},vr=function(t){let s=t.indexOf("?");if(s==-1)return{};let n={};return t.slice(s+1).split("&").forEach(o=>{let[p,...c]=o.split("=");n[p]=c.join("=")}),delete n.x_mock_type,n},T(K,xe),T(K,ue,new Error);var tt=K;var kt=require("crypto");var Me,D=class D extends R{constructor({res:t,req:s,body:n,mockEvent:i,multiValueHeaders:a,isBase64Encoded:o,lambdaName:p,parsedURL:c,requestId:d}){super();l(this,"res");l(this,"mockEvent");l(this,"payload");l(this,"returnError",t=>{if(this.res.writableFinished)return!0;let s=500,n=D.httpErrMsg;t&&D.isEndpointTimeoutError(t.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(s=503,n=D.unavailable):(s=504,n=D.apgTimeoutMsg));let i=[["Date",new Date().toUTCString()],["Content-Type",D.contentType.json],["Content-Length",String(n.length)],D.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(s,i),this.res.end(n)});T(this,Me,t=>{let s="",n=typeof t;if(n=="string"||n=="number"||n=="boolean")s=String(t);else if(t===null)s="";else throw new Error("");return s});l(this,"sendV1Response",t=>{let s=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from((0,kt.randomUUID)()).toString("base64").slice(0,16)],D.keepAlive],n=200;if(!t||isNaN(t.statusCode))throw w.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'. Received:`),console.log(t),new Error;n=t.statusCode,t.headers&&typeof t.headers=="object"&&!Array.isArray(t.headers)&&Object.entries(t.headers).forEach(([d,m])=>{let f=D.normalizeHeaderKey(d),u=v(this,Me).call(this,m);s.push([f,u])}),t.multiValueHeaders&&typeof t.multiValueHeaders=="object"&&!Array.isArray(t.multiValueHeaders)&&Object.entries(t.multiValueHeaders).forEach(([d,m])=>{let f=D.normalizeHeaderKey(d);if(!Array.isArray(m))throw new Error;m.map(h=>v(this,Me).call(this,h)).forEach(h=>{s.push([f,h])})});let i=t.body;if(t.isBase64Encoded&&i){if(typeof i!="string")throw new Error;let d=Buffer.from(i,"base64").toString();if(Buffer.from(d).toString("base64")!=i)throw w.RED("response body is not properly base64 encoded"),new Error;i=d}s.findIndex(d=>d[0].toLowerCase()=="content-type")==-1&&s.push(["Content-Type",D.contentType.json]);let o=s.findIndex(d=>d[0].toLowerCase()=="content-length");o!=-1&&s.splice(o,1);let p=typeof i;p=="number"||p=="boolean"?i=String(i):i&&p!="string"&&w.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let c=n==204?"0":i?String(Buffer.from(i).byteLength):"0";s.push(["Content-Length",c]),this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(i)});l(this,"sendV2Response",t=>{var n;this.res.setHeader("Apigw-Requestid",Buffer.from((0,kt.randomUUID)()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),t?(typeof t.headers=="object"&&!Array.isArray(t.headers)&&Object.keys(t.headers).filter(a=>a!=="Apigw-Requestid"&&a!=="Date").forEach(a=>{this.res.setHeader(a,t.headers[a])}),t.statusCode?(this.res.statusCode=t.statusCode,(n=t.cookies)!=null&&n.length&&this.res.setHeader("Set-Cookie",t.cookies)):this.res.statusCode=200):this.res.statusCode=200;let s="";if(!t)return this.res.end();if(typeof t=="object"&&typeof t.body=="string"&&(s=t.body,t.isBase64Encoded)){let i=Buffer.from(s,"base64").toString();if(Buffer.from(i).toString("base64")!=s)throw w.RED("response body is not properly base64 encoded"),new Error;s=i}typeof t=="string"?(this.res.setHeader("Content-Type",D.contentType.json),s=t):typeof t=="object"&&!t.statusCode&&(this.res.setHeader("Content-Type",D.contentType.json),s=JSON.stringify(t)),this.res.end(s)});l(this,"sendResponse",t=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(t):this.sendV2Response(t)});this.res=t,this.mockEvent=i,this.payload=i.version==1?D.createApgV1Event({req:s,mockEvent:i,parsedURL:c,lambdaName:p,multiValueHeaders:a,isBase64Encoded:o,requestId:d,body:n}):D.createApgV2Event({req:s,mockEvent:i,parsedURL:c,requestId:d,isBase64Encoded:o,body:n})}};Me=new WeakMap,l(D,"skipHeaders",["connection","content"]),l(D,"createApgV2Event",({req:t,mockEvent:s,parsedURL:n,requestId:i,isBase64Encoded:a,body:o})=>{var k,N,E;let{method:p,headers:c}=t,d=D.getPathParameters(s,n),m,f=(k=s.methods.find(P=>P==p))!=null?k:"ANY",u={},h="";for(let P of Array.from(new Set(n.searchParams.keys()))){let M=n.searchParams.getAll(P);h+=`&${M.map(q=>encodeURI(`${P}=${q}`)).join("&")}`,u[P]=M.join(",")}h&&(h=h.slice(1));let y=s.paths[0]=="/*"?"$default":`${f} ${n.pathname}`,b=new Date,g="127.0.0.1",x=(N=c.host)!=null&&N.startsWith("localhost")?g:c.host?c.host.split(":")[0]:g,A={version:"2.0",routeKey:y,rawPath:n.pathname,rawQueryString:h,headers:D.getCustomHeaders(t,s),requestContext:{accountId:String(D.accountId),apiId:D.apiId,domainName:`localhost:${D.port}`,domainPrefix:"localhost",http:{method:p,path:n.pathname,protocol:"HTTP/1.1",sourceIp:x,userAgent:(E=c["user-agent"])!=null?E:""},requestId:i,routeKey:y,stage:"$default",time:b.toISOString(),timeEpoch:b.getTime()}};return o?(A.body=o,A.isBase64Encoded=a):A.isBase64Encoded=!1,Object.keys(u).length&&(A.queryStringParameters=u),Object.keys(d).length&&(A.pathParameters=d),c.cookie&&(A.cookies=c.cookie.split("; ")),m=A,m.headers["x-mock-type"]&&delete m.headers["x-mock-type"],m}),l(D,"createApgV1Event",({req:t,mockEvent:s,parsedURL:n,lambdaName:i,isBase64Encoded:a,requestId:o,body:p})=>{let{method:c}=t,d={};s.proxy=="httpApi"&&(d.version="1.0");let m=s.paths[0];d.resource=m,d.path=n.pathname,d.httpMethod=c;let{headers:f,multiValueHeaders:u,apiKey:h}=D.getApiGV1Headers(t,s);d.headers=f,d.multiValueHeaders=u;let y=String(t.socket.remoteAddress),b=Object.fromEntries(n.searchParams);d.queryStringParameters=Object.keys(b).length?b:null;let g=D.getMultiValueQueryStringParameters(n.searchParams);d.multiValueQueryStringParameters=Object.keys(g).length?g:null;let x=new Date,A={accountId:String(D.accountId),apiId:D.apiId,domainName:`localhost:${D.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:c,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:y,user:null,userAgent:t.headers["user-agent"],userArn:null},path:n.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:x.toISOString(),requestTimeEpoch:x.getTime(),resourceId:"exhmtv",resourcePath:m};s.proxy=="httpApi"?(A.identity.cognitoAmr=null,A.stage="$default"):(A.stage="dev",s.private&&(A.identity.apiKey=h,A.identity.apiKeyId="abcdefghjk")),d.requestContext=A;let k=D.getPathParameters(s,n);return d.pathParameters=Object.keys(k).length?k:null,d.stageVariables=null,d.body=p!=null?p:null,d.isBase64Encoded=p?a:!1,d});var Ee=D;var Ar=require("crypto");var ds=(r,e)=>{if(r.get("x_mock_type")!==null)return r.get("x_mock_type");if(e["x-mock-type"])return Array.isArray(e["x-mock-type"])?e["x-mock-type"][0]:e["x-mock-type"]},ms=r=>r.mockEvent.kind=="alb"?new tt(r):new Ee(r),us=(r,e,t)=>{if(e.private){if(!t.length)return console.log("\x1B[31mPrivate http endpoints require API Key to be defined in serverless.yml\x1B[0m"),!1}else return!0;for(let s=0;s<r.rawHeaders.length;s++)if(r.rawHeaders[s].toLowerCase()=="x-api-key"){let i=r.rawHeaders[s+1];if(t.includes(i))return!0}return!1},wr=(r,e,t,s)=>S(void 0,null,function*(){let{url:n,method:i,headers:a,rawHeaders:o}=r,{searchParams:p}=t,c=ds(p,a),d=R.getMultiValueHeaders(o),m=R.normalizeSearchParams(p,decodeURI(n)),f=F.findHandler({headers:d,query:m,method:i,path:decodeURIComponent(t.pathname),kind:c});if(!f)return;let{event:u,handler:h}=f;try{gr(a,u.kind)}catch(N){return e.statusCode=400,e.setHeader("Content-Type",R.contentType.text),e.end(N.message)}if(!us(r,u,s))return e.statusCode=403,e.setHeader("Content-Type",R.contentType.json),e.end(R.apigForbiddenErrMsg);u.async&&(e.statusCode=200,e.end());let y=(0,Ar.randomUUID)(),b=R.getIsBase64Encoded(a),g=yield ae(r,b),x=a["content-type"];if((!x||x=="application/json"||x=="application/json; charset=utf-8")&&u.kind=="apg"&&u.schema&&u.proxy=="http"){let N;try{N=JSON.parse(g)}catch(P){return e.statusCode=400,e.setHeader("Content-Type",R.contentType.json),e.end(R.apigJsonParseErrMsg)}if(!u.schema(N)){e.statusCode=400,e.setHeader("Content-Type",R.contentType.json);let P=u.schema.errors.map(M=>`instancePath '${M.instancePath}' ${M.message}`).join(", ");return e.end(JSON.stringify({message:`[${P}]`}))}}let k=ms({req:r,res:e,body:g,isBase64Encoded:b,multiValueHeaders:d,mockEvent:u,lambdaName:h.outName,parsedURL:t,requestId:y});try{let N=yield h.invoke(k.payload,u);N instanceof _&&(N=N.getParsedResponse()),k.sendResponse(N)}catch(N){return k.returnError(N)}return!0});var rt=class{constructor(e){l(this,"err");l(this,"isMounted",!0);l(this,"mount",()=>{});l(this,"unmount",()=>{});l(this,"invoke",()=>S(this,null,function*(){throw this.err}));l(this,"onComplete",()=>{});this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}};var xr=require("events"),Er=require("worker_threads"),kr=U(require("path"));var nt=class extends xr.EventEmitter{constructor({name:t,outName:s,timeout:n,memorySize:i,environment:a,handlerPath:o,handlerName:p,esOutputPath:c}){super();l(this,"_worker");l(this,"isMounted",!1);l(this,"_isLoading",!1);l(this,"invoke");l(this,"mount");l(this,"unmount");l(this,"name");l(this,"outName");l(this,"timeout");l(this,"memorySize");l(this,"environment");l(this,"handlerPath");l(this,"handlerName");l(this,"esOutputPath");l(this,"onComplete",(t,s)=>{var n;(n=this._worker)==null||n.postMessage({channel:"complete",awsRequestId:t,timeout:s})});this.name=t,this.outName=s,this.timeout=n,this.memorySize=i,this.environment=a,this.handlerPath=o,this.handlerName=p,this.esOutputPath=c,this.mount=()=>S(this,null,function*(){this._isLoading?(this.setMaxListeners(0),yield new Promise((d,m)=>{this.once("loaded",f=>{f?d(void 0):m()})})):this.isMounted||(this._isLoading=!0,yield this.importHandler())}),this.unmount=()=>{var d;(d=this._worker)==null||d.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=y=>S(this,[y],function*({event:d,info:m,clientContext:f,response:u,awsRequestId:h}){return new Promise((b,g)=>{this._worker.postMessage({channel:"exec",data:{event:d,clientContext:f},awsRequestId:h});let x=u!=null?u:new _(m);function A(k,N,E,P){switch(k){case"return":case"succeed":case"done":this.removeListener(h,A),b(N);break;case"fail":this.removeListener(h,A),g(N);break;case"stream":E=="write"?x.write(N,P):E=="ct"?x.setHeader("Content-Type",N):E=="timeout"?(this.removeListener(h,A),x.destroy(),g(N)):(this.removeListener(h,A),x.end(N),b(x instanceof _?x:void 0));break;default:this.removeListener(h,A),g(new Error("Unknown error"));break}}this.on(h,A)})})}importHandler(){return S(this,null,function*(){yield new Promise((t,s)=>{let n={name:this.name,env:this.environment,execArgv:["--enable-source-maps"],workerData:{name:this.name,timeout:this.timeout,memorySize:this.memorySize,esOutputPath:this.esOutputPath,handlerPath:this.handlerPath,handlerName:this.handlerName,debug:w.getDebug()}};this._worker=new Er.Worker(kr.default.resolve(__dirname,"./lib/runtime/runners/node/index.js"),n),this._worker.setMaxListeners(0);let i=a=>{this.isMounted=!1,this._isLoading=!1,w.RED("Lambda execution fatal error"),console.error(a),this.emit("loaded",!1),s(a)};this._worker.on("message",a=>{let{channel:o,data:p,awsRequestId:c,type:d,encoding:m}=a;o=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this._worker.removeListener("error",i),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),t(void 0)):o=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,w.RED(`${d} Uncaught exceptions`),console.error(p.error),p.solution&&(w.BR_BLUE("Solution:"),console.log(p.solution))):this.emit(c,o,p,d,m)}),this._worker.on("error",i),this._worker.postMessage({channel:"import"})})})}};var Rr=require("child_process"),ke=U(require("path")),Ir=require("fs"),Rt=require("fs/promises");var fs=process.cwd(),W=class W{constructor({name:e,outName:t,timeout:s,memorySize:n,environment:i,handlerPath:a,handlerName:o,runtime:p},c){l(this,"invoke");l(this,"mount");l(this,"unmount");l(this,"name");l(this,"outName");l(this,"timeout");l(this,"memorySize");l(this,"environment");l(this,"handlerPath");l(this,"pyModulePath");l(this,"handlerDir");l(this,"handlerName");l(this,"runtime");l(this,"bin");l(this,"python");l(this,"isMounted",!1);l(this,"watchers",[]);l(this,"filesTime",new Map);l(this,"watcherListener");l(this,"emitRebuild");l(this,"setWatchFiles",e=>S(this,null,function*(){try{let t=e.split(W.WATCH),n=t[t.length-1].split(W.WATCHEND)[0],i=JSON.parse(n).map(a=>`${a.replace(/\./g,ke.default.sep)}.py`);for(let a of i)try{yield(0,Rt.access)(a),this.watchers.push((0,Ir.watch)(a,{persistent:!1},this.watcherListener))}catch(o){}}catch(t){console.log(t)}}));l(this,"load",()=>{this.bin||(this.bin=process.platform==="win32"?"python":this.runtime.includes(".")?this.runtime.split(".")[0]:this.runtime),this.python=(0,Rr.spawn)(this.bin,[W.wrapper,this.pyModulePath,this.handlerName,String(this.timeout)],{env:this.environment}),this.python.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0});l(this,"onComplete",e=>{});this.name=e,this.outName=t,this.timeout=s,this.memorySize=n,this.environment=i,this.handlerName=o,this.runtime=p,this.emitRebuild=c;let d=ke.default.resolve(a);this.handlerDir=ke.default.dirname(d),this.handlerPath=ke.default.basename(d,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(fs,"").replace(/\/|\\/g,".").slice(1),this.mount=()=>S(this,null,function*(){if(this.python)return;let m=`${this.handlerDir}/${this.handlerPath}.py`;try{yield(0,Rt.access)(m),this.load()}catch(f){console.error(`Can not find ${this.name}'s handler at: "${m}"`),process.exit(1)}}),this.unmount=m=>{var f;m&&((f=this.python)==null||f.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=y=>S(this,[y],function*({event:m,info:f,clientContext:u,awsRequestId:h}){return new Promise((b,g)=>{let x=JSON.stringify({event:m,awsRequestId:h,context:u!=null?u:""}),A=N=>{let E=null,P=N.toString();try{let M=P.includes(W.WATCH);if(M&&this.setWatchFiles(P),P.includes(W.DELIMITER)){let q=P.split(W.DELIMITER),Z=q[q.length-1].split(W.DELIMITEREND)[0];if(q.length>1){let ee;M?ee=q[0].split(W.WATCHEND)[1]:ee=q.slice(0,-1).join(` `),ee.trim()&&console.log(ee)}Z&&(E=JSON.parse(Z)),this.python.stdout.removeListener("data",A),this.python.stderr.removeListener("data",k),b(E)}else if(P.trim()){let q;M?q=P.split(W.WATCHEND)[1]:q=P,q.trim()&&console.log(q)}}catch(M){console.log("err",M),g(M)}};this.python.stdout.on("data",A);let k=N=>{let E=N.toString();if(E.includes(W.ERR_RESPONSE))try{E=JSON.parse(E.split(W.ERR_RESPONSE)[1]),E.requestId=h}catch(P){}finally{this.python.stdout.removeListener("data",A),this.python.stderr.removeListener("data",k),g(E)}else console.log(E)};this.python.stderr.on("data",k),this.python.stdin.write(`${x} `)})}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(m=>m.close()),this.watchers=[],this.emitRebuild())}}};l(W,"wrapper",__dirname.replace(`${ke.default.sep}dist`,"/src/lib/runtime/runners/python/index.py")),l(W,"DELIMITER","__|response|__"),l(W,"DELIMITEREND","__|responseEnd|__"),l(W,"ERR_RESPONSE","__|error|__"),l(W,"WATCH","__|watch|__"),l(W,"WATCHEND","__|watchEnd|__");var st=W;var Pr=require("child_process"),Fe=U(require("path")),Nr=require("fs"),It=require("fs/promises");var Q=class Q{constructor({name:e,outName:t,timeout:s,memorySize:n,environment:i,handlerPath:a,handlerName:o,runtime:p},c){l(this,"invoke");l(this,"mount");l(this,"unmount");l(this,"name");l(this,"outName");l(this,"timeout");l(this,"memorySize");l(this,"environment");l(this,"handlerPath");l(this,"modulePath");l(this,"handlerDir");l(this,"handlerName");l(this,"runtime");l(this,"bin");l(this,"ruby");l(this,"isMounted",!1);l(this,"emitRebuild");l(this,"watcherListener");l(this,"watchers",[]);l(this,"setWatchFiles",e=>S(this,null,function*(){try{let t=e.split(Q.WATCH),s=t[t.length-1],n=JSON.parse(s);n.push(this.modulePath);for(let i of n)try{yield(0,It.access)(i),this.watchers.push((0,Nr.watch)(i,{persistent:!1},this.watcherListener))}catch(a){}}catch(t){console.log(t)}}));l(this,"load",()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=(0,Pr.spawn)(this.bin,[Q.wrapper,this.modulePath,this.handlerName,this.name,String(this.timeout)],{env:this.environment,shell:!0}),this.ruby.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0});l(this,"onComplete",e=>{});this.name=e,this.outName=t,this.timeout=s,this.memorySize=n,this.environment=i,this.handlerName=o,this.runtime=p,this.emitRebuild=c;let d=Fe.default.resolve(a);this.handlerDir=Fe.default.dirname(d),this.handlerPath=Fe.default.basename(d,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=()=>S(this,null,function*(){if(!this.ruby)try{yield(0,It.access)(this.modulePath),this.load()}catch(m){console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}}),this.unmount=m=>{var f;m&&((f=this.ruby)==null||f.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=y=>S(this,[y],function*({event:m,info:f,clientContext:u,awsRequestId:h}){return new Promise((b,g)=>{let x=JSON.stringify({event:m,awsRequestId:h,context:u!=null?u:""}),A=N=>{let E=null,P=N.toString();try{if(P.includes(Q.WATCH))this.setWatchFiles(P);else if(P.includes(Q.DELIMITER)){let M=P.split(Q.DELIMITER),q=M[M.length-1];if(M.length>1){let Z=M.slice(0,-1).join(` `);Z.trim()&&console.log(Z)}q&&(E=JSON.parse(q)),this.ruby.stdout.removeListener("data",A),this.ruby.stderr.removeListener("data",k),b(E)}else P.trim()&&console.log(P)}catch(M){g(M)}};this.ruby.stdout.on("data",A);let k=N=>{let E=N.toString();if(E.includes(Q.ERR_RESPONSE))try{E=JSON.parse(E.split(Q.ERR_RESPONSE)[1]),E.requestId=h}catch(P){}finally{this.ruby.stdout.removeListener("data",A),this.ruby.stderr.removeListener("data",k),g(E)}else console.log(E)};this.ruby.stderr.on("data",k),this.ruby.stdin.write(`${x} `)})}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(m=>m.close()),this.watchers=[],this.emitRebuild())}}};l(Q,"wrapper",__dirname.replace(`${Fe.default.sep}dist`,"/src/lib/runtime/runners/ruby/index.rb")),l(Q,"DELIMITER","__|response|__"),l(Q,"ERR_RESPONSE","__|error|__"),l(Q,"WATCH","__|watch|__");var it=Q;var Dr=require("crypto");var Tr=(r,e,t)=>{switch(r){case"=":return e===t;case">":return e>t;case"<":return e<t;case">=":return e>=t;case"<=":return e<=t;default:return!1}},Lr={exists:(r,e,t)=>{if(t===!0)return e in r&&!Pt(r[e]);if(t===!1)return!(e in r)},prefix:(r,e,t)=>{let s=typeof r[e]=="string"?r[e]:void 0;return s?s.startsWith(t):!1},suffix:(r,e,t)=>{let s=typeof r[e]=="string"?r[e]:void 0;return s?s.endsWith(t):!1},numeric:(r,e,t)=>{if(!(e in r))return!1;let s=[],[n,i]=t;if(s.push(Tr(n,r[e],i)),t.length==4){let[,,a,o]=t;s.push(Tr(a,r[e],o))}return s.every(a=>a===!0)},"anything-but":(r,e,t)=>{let s=typeof r[e]=="string"?r[e]:void 0;return s?!t.includes(s):!1},"equals-ignore-case":(r,e,t)=>typeof(r==null?void 0:r[e])!="string"?!1:r[e].toLowerCase()==t.toLowerCase()},hs=(r,e,t)=>{if(t===null)return r[e]===null;let s=typeof t;if(s=="string")return r[e]==t;if(s=="object"&&!Array.isArray(t)){let n=[];for(let[i,a]of Object.entries(t))i in Lr&&n.push(Lr[i](r,e,a));return n.every(i=>i===!0)}return!1},ys=Array.isArray,gs=r=>r&&typeof r=="object"&&!Array.isArray(r),at=(r,e)=>{let t=[];for(let[s,n]of Object.entries(r)){let i=[];ys(n)?(s=="$or"?i=n.map(a=>at(a,e)):i=n.map(a=>hs(e,s,a)),t.push(i.some(a=>a===!0))):gs(e[s])&&at(n,e[s])?t.push(!0):t.push(!1)}return t.every(s=>s===!0)};var fe=class{constructor(e,t){this.config=e;this.legacyDefinition=t;l(this,"UUID",(0,Dr.randomUUID)());l(this,"LastModified",Date.now());l(this,"LastProcessingResult","No records processed");l(this,"State","Creating");l(this,"StateTransitionReason","User action")}filterRecords(e){var n;let t=[],s=[];if(!Array.isArray((n=this.config.FilterCriteria)==null?void 0:n.Filters))return[e,[]];for(let i of e)this.config.FilterCriteria.Filters.map(p=>at(JSON.parse(p.Pattern),i)).find(p=>p===!0)?t.push(i):s.push(i);return[t,s]}};l(fe,"SOURCES",[]);var le=require("@aws-sdk/client-sqs");var na=require("@aws-sdk/client-sqs");var G=class{static setSqsClient(e){return S(this,null,function*(){try{let{SQSClient:t}=yield import("@aws-sdk/client-sqs");this.sqs=new t(e)}catch(t){}})}};l(G,"sqs");var Or=10,jr=0,bs=(r,e)=>G.sqs.send(new le.ReceiveMessageCommand({QueueUrl:r,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:e})),Ss=r=>G.sqs.send(new le.GetQueueUrlCommand({QueueName:r})),vs=r=>G.sqs.send(new le.GetQueueAttributesCommand({QueueUrl:r,AttributeNames:["All"]})),Mr=(r,e)=>S(void 0,null,function*(){for(let t of Vr(e,10)){if(!t.length)continue;let s=t.map((n,i)=>({Id:`id-${i+1}`,ReceiptHandle:n}));try{yield G.sqs.send(new le.DeleteMessageBatchCommand({QueueUrl:r,Entries:s}))}catch(n){}}}),As=r=>{if(!r)return{};let e={};for(let[t,s]of Object.entries(r)){e[t]={};let{StringValue:n,BinaryValue:i,DataType:a}=s;a.startsWith("B")?e[t].binaryValue=i:e[t].stringValue=n,e[t].stringListValues=[],e[t].binaryListValues=[],e[t].dataType=a}return e},ws=(r,e)=>{let{MessageId:t,Body:s,MD5OfBody:n,ReceiptHandle:i,Attributes:a,MessageAttributes:o,MD5OfMessageAttributes:p}=r,c={messageId:t,receiptHandle:i,body:s,attributes:a,messageAttributes:As(o)};return p&&(c.md5OfMessageAttributes=p),c.md5OfBody=n,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},xs=(r,e)=>r.map(t=>ws(t,e)),te,qe,he,Fr,Tt,Nt=class{constructor(e,t,s,n,i,a){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=t;this.lambdaName=s;this.QueueUrl=n;this.ReportBatchItemFailures=i;this.legacyDefinition=a;T(this,he);l(this,"available",!0);T(this,te,[]);T(this,qe,!1)}setRecord(e){return S(this,null,function*(){v(this,te).length||I(this,he,Fr).call(this),v(this,te).push(e),(v(this,te).length==this.BatchSize||!this.available)&&(this.available=!1,yield I(this,he,Tt).call(this))})}};te=new WeakMap,qe=new WeakMap,he=new WeakSet,Fr=function(){setTimeout(()=>S(this,null,function*(){this.available=!1,v(this,qe)||(yield I(this,he,Tt).call(this))}),this.MaximumBatchingWindowInSeconds*1e3)},Tt=function(){return S(this,null,function*(){$(this,qe,!0);let e=v(this,te).map(t=>t.receiptHandle);try{let s=yield F.handlers.find(n=>n.name==this.lambdaName||n.outName==this.lambdaName).invoke({Records:v(this,te)},{kind:"sqs",event:this.legacyDefinition});this.ReportBatchItemFailures&&(e=Ur(v(this,te),s)),yield Mr(this.QueueUrl,e)}catch(t){}})};var oe,He,We,J,qr,Hr,ce,Wr,$e,Lt,$r,ot=class extends fe{constructor(t,s){var i;super(t,s);this.config=t;this.legacyDefinition=s;T(this,J);T(this,oe,[]);l(this,"QueueName","");l(this,"QueueUrl","");T(this,He);T(this,We);T(this,ce,1500);T(this,$e);let n=this.config.EventSourceArn.split(":");this.QueueName=n[n.length-1],$(this,We,((i=this.config.FunctionResponseTypes)==null?void 0:i[0])=="ReportBatchItemFailures")}pool(){return S(this,null,function*(){if(!G.sqs)return;let{QueueUrl:t}=yield Ss(this.QueueName);this.QueueUrl=t,yield this.enable()})}cleanBatchs(){for(let t=0;t<v(this,oe).length;t++)v(this,oe)[t].available||v(this,oe).splice(t,1)}enable(){return S(this,null,function*(){this.State="Enabling";try{yield I(this,J,Wr).call(this),this.config.Enabled=!0,this.State="Enabled",yield I(this,J,Lt).call(this)}catch(t){console.error(t)}})}disable(){this.config.Enabled=!1,clearTimeout(v(this,He)),this.State="Disabling"}};oe=new WeakMap,He=new WeakMap,We=new WeakMap,J=new WeakSet,qr=function(){let t=v(this,oe).find(n=>n.available);if(t)return t;let s=new Nt(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.QueueUrl,v(this,We),this.legacyDefinition);return v(this,oe).push(s),s},Hr=function(t){return S(this,null,function*(){for(let s of t)yield I(this,J,qr).call(this).setRecord(s)})},ce=new WeakMap,Wr=function(){return S(this,null,function*(){let t=0,s=2e3,n=()=>S(this,null,function*(){try{let{Attributes:i}=yield vs(this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))t++,v(this,ce)<=2e4&&$(this,ce,v(this,ce)+200),t==5&&(s=2e3);else{t=0,s=400;let o=v(this,ce);$(this,ce,350),o>=1600&&(yield I(this,J,Lt).call(this,!0))}}catch(i){s=2e3}this.cleanBatchs(),$(this,He,setTimeout(n,s))});yield n()})},$e=new WeakMap,Lt=function(t){return S(this,null,function*(){t&&clearTimeout(v(this,$e));let s=()=>S(this,null,function*(){if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:n}=yield bs(this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(n){let i=xs(n,this.config.EventSourceArn),a=yield I(this,J,$r).call(this,i);yield I(this,J,Hr).call(this,a)}}catch(n){}$(this,$e,setTimeout(s,v(this,ce)))});yield s()})},$r=function(t){return S(this,null,function*(){let s=t.map(o=>{let p=L({},o);try{p.body=JSON.parse(p.body)}catch(c){}return p}),[n,i]=this.filterRecords(s);yield Mr(this.QueueUrl,i.map(o=>o.receiptHandle));let a=[];for(let o of n)a.push(...t.filter(p=>p.messageId==o.messageId));return a})};var zr=r=>S(void 0,null,function*(){for(let e of r)for(let t of e.sqs){let s=t.arn;if(!s)if(t.name)s=`arn:aws:sqs:us-east-1:123456789012:${t.name}`;else continue;let n;if(Array.isArray(t.filterPatterns)){n=[];for(let a of t.filterPatterns)Pt(a)&&n.push({Pattern:JSON.stringify(a)});n.length||(n=void 0)}let i=new ot({BatchSize:typeof t.batchSize=="number"?t.batchSize:Or,Enabled:t.enabled,EventSourceArn:s,FunctionName:e.name,FunctionResponseTypes:t.functionResponseType,FilterCriteria:n?{Filters:n}:void 0,MaximumBatchingWindowInSeconds:typeof t.maximumBatchingWindow=="number"?t.maximumBatchingWindow:jr},t);if(fe.SOURCES.push(i),i.config.Enabled)try{yield i.pool()}catch(a){w.RED(`Failed to start EventSourceMapping ${i.config.EventSourceArn} Please verify provided SQS Client Config validity.`),console.error(a)}}}),Es=/(-|\w+)/g,ks=r=>r.length<81&&r.replace(Es,"")=="",Ur=(r,e)=>{if(typeof e===void 0||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return r.map(s=>s.receiptHandle);let t=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(s=>!s.itemIdentifier||!ks(s.itemIdentifier)||!r.find(n=>n.messageId==s.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return r.forEach(s=>{e.batchItemFailures.find(i=>i.itemIdentifier==s.messageId)||t.push(s.receiptHandle)}),t}},Vr=(r,e)=>{